我试图找到与文章相关的前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;
答案 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
)