高级计数并加入Rails

时间:2010-06-01 19:01:30

标签: sql ruby-on-rails activerecord

我试图找到与文章相关的前n个类别,在两者之间建立了一个关系。这是我想要执行的SQL,但除了使用find_by_sql方法之外,我不确定如何使用ActiveRecord执行此操作。有没有办法用ActiveRecord方法做到这一点:

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;

1 个答案:

答案 0 :(得分:9)

您可以使用find选项来实现相同的查询:

Category.find(:all, 
  :select => '"categories".id, "categories".name, count("articles".id) as counter', 
  :joins => :articles, 
  :group => '"categories".id', 
  :order => 'counter DESC', 
  :limit => 5
)