2009-06-16 85 views
0

假裝我有一個模型,發佈has_many:comments。我如何才能顯示有評論的帖子?一個關聯的ActiveRecord條件(Rails)

我對named_scope感到有點不舒服,但我不知道如何將Post.comments(或self.comments)放置在期望符號的條件散列中。

class Post < ActiveRecord::Base 
    has_many :comments 
    named_scope :with_comments, :conditions => [#self.comments.length > 0] 
end 

我在評論區域寫什麼?

謝謝!

回答

1

更好的可能是把一個counter_cache上發表。

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

然後你只需要做1個查詢而不是2個。

Post.find(:all, :conditions => ["counter_cache > 0"])

2

你應該能夠剛剛加入對你的意見表,並確保選擇不同的行

named_scope :with_comments, :joins => :comments, :select => 'DISTINCT posts.*' 
+0

看起來很棒。我如何傳遞參數讓我手動輸入屬性名稱。我的帖子表有一個名爲postid的pk,而評論表有一個名爲post_id的fk。我知道如何在關聯中手動設置pks和fks,如何使用named_scope來完成它?再次感謝,這真是一個質量反應。 – user94154 2009-06-17 00:49:25

+0

只需用您想要的連接替換:連接選項即可。你可能想要類似下面的東西, :joins =>'INNER JOIN'comments「ON comments.post_id = posts.postid' – slillibri 2009-06-17 22:55:05