2010-11-30 63 views
4

我有一個簡單的rails 3博客應用程序,其中帖子有很多評論和評論屬於帖子。查找超過既定數量的評論的所有帖子

我想創建一個範圍,將獲取所有超過5條評論的帖子。 沒有計數器緩存列的情況下,這樣做的最佳方式是什麼?

回答

8

像這樣,也許?

Post.select('posts.*, count(comments.id) as comment_count'). 
    joins(:comments). 
    group('posts.id'). 
    having('comment_count > 5') 
+0

這似乎不適用於我。它只返回第一條記錄。另外,comment_count被設置爲db中所有註釋的總數。 – KJF 2010-11-30 15:50:23

0

從noodl很好的答案...謝謝你!

我需要找到 - 堅持使用原來的問題的示例類 - 4個職位,是最近一次是在... noodl的回答略有變異評論的伎倆:

Post.select('posts.*, max(comments.created_at) as last_commented_at'). 
    joins(:comments). 
    group('posts.id'). 
    order('last_commented_at DESC'). 
    limit(4) 

謝謝!

4

Postgres 9.1我不得不這樣設置,因爲postgres並不樂意在條件計算字段或類似的東西上。

Post.select('posts.*, count(comments.id) as comment_count'). 
    joins(:comments). 
    group('posts.id'). 
    having('count(comments.id) > 5') 
相關問題