2012-07-18 57 views
1

One Post有很多意見。我想選擇的所有帖子,其中comments.count大於5選擇所有帖子where comments.count> = 10

事情是這樣的:Post.all.joins(:評論).having(「數> = 5」)

+0

您是否在尋找RoR的代碼,或者是你想編寫一個SQL查詢? – leonsas 2012-07-18 16:24:56

+0

RoR最好:) – Hendrik 2012-07-18 16:31:16

+0

不能幫忙,對不起! – leonsas 2012-07-18 16:36:44

回答

3

如果添加一個comments_count列到你的職位表,補充一點:

class Comment < ActiveRecord::Base 
    belongs_to :post, :counter_cache => true 
    .. 
end 

然後當你保存後,就會更新計數器。在這一點上,查詢非常簡單:

Post.where("comments_count >= ?", 5).all 

或者,您可以放入純SQL代碼。但人,只是去櫃檯

相關:Rails query that sorts based on the count of a nested model?