代码之家  ›  专栏  ›  技术社区  ›  Harish Shetty

如何向include生成的连接添加附加条件?

  •  2
  • Harish Shetty  · 技术社区  · 16 年前

    LEFT OUTER JOIN :include 中的选项 ActiveRecord 寻找者。

    class Post
      has_many :comments
    end
    
    class Comment
      belongs_to :post
      has_many   :comment_votes
    end
    
    class CommentVote
      belongs_to :comment
    end
    

    现在让我们假设我想找到最后10个帖子及其相关的评论和投票。

    Post.find.all(:limit => 10, :order => "created_at DESC",
        :include => [{:comments => :comment_votes])
    

    我不能添加条件来检查向上投票,因为它将忽略没有向上投票的职位。因此,条件必须转到为 comment_votes . 我希望有一个语法,如:

    Post.find.all(:limit => 10, :order => "created_at DESC",
        :include => [{:comments => [:comment_votes, :on => "comment_votes.vote > 0"])
    

    你以前遇到过这样的问题吗?你用取景器解决了这个问题吗?我希望从社区听到一些有趣的想法。

    附言: 我可以编写一个joinsql来获得预期的结果并将结果缝合在一起。我要确保在走这条路之前没有其他选择。

    1 回复  |  直到 12 年前
        1
  •  3
  •   jrallison    16 年前

    如果我没弄错你的问题,像这样的方法可能有用:

    class Comment
      belongs_to :post
      has_many   :comment_votes
      has_many   :up_votes, :class_name => "CommentVote", :conditions => "vote > 0"
    end
    

    那么你的发现者将是:

    Post.find.all(:limit => 10, :order => "created_at DESC",
    :include => {:comments => :up_votes})
    

    注意:我没有测试这个。

    推荐文章