2009-06-16 84 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