Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advanced count and join in Rails

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;
like image 253
trobrock Avatar asked Jun 01 '10 19:06

trobrock


1 Answers

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
)
like image 79
Voyta Avatar answered Oct 24 '22 09:10

Voyta