Advanced count and join in Rails
Posted
by trobrock
on Stack Overflow
See other posts from Stack Overflow
or by trobrock
Published on 2010-06-01T19:01:30Z
Indexed on
2010/06/01
19:03 UTC
Read the original article
Hit count: 291
I am try to find the top n
number of categories as they relate to articles, there is a habtm relationship set up between the two. This is the SQL I want to execute, but am unsure of how to do this with ActiveRecord, aside from using the find_by_sql
method. is there any way of doing this with ActiveRecord methods:
SELECT "categories".id, "categories".name, count("articles".id) as counter FROM "categories"
JOIN "articles_categories" ON "articles_categories".category_id = "categories".id
JOIN "articles" ON "articles".id = "articles_categories".article_id
GROUP BY "categories".id
ORDER BY counter DESC
LIMIT 5;
© Stack Overflow or respective owner