ActiveRecord 关联条件 (Rails)

发布于 2024-07-24 09:47:57 字数 336 浏览 7 评论 0原文

假装我有一个模型,发布其中有_许多:评论。 如何只显示有评论的帖子?

我对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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

少女情怀诗 2024-07-31 09:47:57

您应该能够仅加入评论表,确保选择不同的行

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

You should be able to just join against your comments table, making sure to select the distinct rows

named_scope :with_comments, :joins => :comments, :select => 'DISTINCT posts.*'
很酷又爱笑 2024-07-31 09:47:57

更好的办法可能是在 Post 上放置一个 counter_cache。

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

那么您只需要执行 1 次查询,而不是两次。

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

Better might be to put a counter_cache on Post.

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

Then you only need to do 1 query instead of two.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文