【问题标题】:ActiveRecord conditions of an association (Rails)关联的 ActiveRecord 条件(Rails)
【发布时间】:2009-06-16 21:30:40
【问题描述】:

假装我有一个模型,Post,其中 has_many :cmets。我怎样才能只显示有 cmets 的帖子?

我对 named_scope 有点满意,但我不知道如何将 Post.cmets(或 self.cmets)放入需要符号的 :conditions 哈希中。

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

我在评论区写什么?

谢谢!

【问题讨论】:

    标签: ruby-on-rails activerecord named-scope


    【解决方案1】:

    您应该能够只加入您的 cmets 表,确保选择不同的行

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

    【讨论】:

    • 看起来棒极了。如何传递参数,让我手动输入属性名称。我的帖子表有一个名为 postid 的 pk,而 cmets 表有一个名为 post_id 的 fk。我知道如何在关联中手动设置 pks 和 fks,我该如何使用 named_scope 呢?再次感谢,这确实是一个高质量的响应。
    • 只需将 :joins 选项替换为您想要的连接即可。您可能想要类似以下内容, :joins => 'INNER JOIN "cmets" ON cmets.post_id = posts.postid'
    • 在 Rails 中,:joins 默认使用 INNER JOIN
    【解决方案2】:

    最好在 Post 上放置一个 counter_cache。

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

    那么你只需要做 1 个查询而不是 2 个。

    Post.find(:all, :conditions =&gt; ["counter_cache &gt; 0"])

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-16
      • 1970-01-01
      • 2010-10-06
      • 2011-12-15
      • 1970-01-01
      相关资源
      最近更新 更多