ActiveRecord 关联条件 (Rails)
假装我有一个模型,发布其中有_许多:评论。 如何只显示有评论的帖子?
我对named_scope有点满意,但我不知道如何将Post.comments(或self.comments)放入需要符号的:conditions哈希中。
class Post < ActiveRecord::Base
has_many :comments
named_scope :with_comments, :conditions => [#self.comments.length > 0]
end
我在评论区写什么?
谢谢!
Pretend I have a model, Post which has_many :comments. How can I only display posts that have comments?
I am somewhat comfortable with named_scope but I don't know how I can put Post.comments (or self.comments) in the :conditions hash which expects symbols.
class Post < ActiveRecord::Base
has_many :comments
named_scope :with_comments, :conditions => [#self.comments.length > 0]
end
What do I write in the commented area?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该能够仅加入评论表,确保选择不同的行
You should be able to just join against your comments table, making sure to select the distinct rows
更好的办法可能是在 Post 上放置一个 counter_cache。
那么您只需要执行 1 次查询,而不是两次。
Post.find(:all, :conditions => ["counter_cache > 0"])
Better might be to put a counter_cache on Post.
Then you only need to do 1 query instead of two.
Post.find(:all, :conditions => ["counter_cache > 0"])