How to add additional condition to the JOIN generated by include?

Posted by KandadaBoggu on Stack Overflow See other posts from Stack Overflow or by KandadaBoggu
Published on 2010-03-20T05:59:34Z Indexed on 2010/03/20 6:01 UTC
Read the original article Hit count: 192

Filed under:
|

I want to add additional criteria to the LEFT OUTER JOIN generated by the :include option in ActiveRecord finder.

class Post
  has_many :comments
end

class Comment
  belongs_to :post
  has_many   :comment_votes
end

class CommentVote
  belongs_to :comment
end

Now lets say I want to find last 10 posts with their associated comments and the up comment votes.

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

I cant add the condition to check for up votes as it will ignore the posts without the up votes. So the condition has to go the ON clause of the JOIN generated for the comment_votes. I am wishing for a syntax such as:

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

Have you faced such problems before? Did you managed to solve the problem using the current finder? I hope to hear some interesting ideas from the community.

PS: I can write a join SQL to get the expected result and stitch the results together. I want to make sure there is no other alternative before going down that path.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about activerecord