2010-06-01 77 views
5

我嘗試找到頂部n與文章相關的類別數量,兩者之間建立了一種哈比姆關係。這是我想要執行的SQL,但我不確定如何使用ActiveRecord執行此操作,除了使用find_by_sql方法。有沒有與ActiveRecord的方法,這樣做的任何方式:高級計數和加入Rails

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; 

回答

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

優秀的感謝,以爲我試過了,但很明顯,我有什麼錯它 – trobrock 2010-06-02 01:23:00

+0

任何方式後訪問計數值? 'category = Category.find(...)。first; category.counter'? – 2016-06-09 14:01:08