views:

43

answers:

1

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;
A: 

You can use find with options to achieve the same query:

Category.find(:all, 
  :select => '"categories".id, "categories".name, count("articles".id) as counter', 
  :joins => :articles, 
  :group => '"categories".id', 
  :order => 'counter DESC', 
  :limit => 5
)
Voyta
Excellent thanks, thought I tried that but obviously I had something wrong in it
trobrock