开发者

Advanced count and join in Rails

开发者 https://www.devze.com 2023-01-02 01:50 出处:网络
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 wit

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开发者_如何学JAVA".id
JOIN "articles" 
  ON "articles".id = "articles_categories".article_id
GROUP BY "categories".id
ORDER BY counter DESC
LIMIT 5;


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
)
0

精彩评论

暂无评论...
验证码 换一张
取 消