Extending left outer joins when using active eager loading


From the ActiveRecord::Associations::ClassMethods docs, there is the

“for post in Post.find(:all, :include => [ :author, :comments ])”

“That‘ll add another join along the lines of: LEFT OUTER JOIN comments
ON comments.post_id = posts.id”

What can one do to add a DYNAMIC second AND constraint to the left outer
join on clause such as:

“LEFT OUTER JOIN comments ON comments.post_id = posts.id AND
comment.person_id = ?”

I can only do this via a custom association where the comment.person_id
value is hard-coded, but it’s of very limited use. I want
comment.person_id to reflect the logged in user or a session id, etc.
(Perhaps a limitation of AR?)

I’ve always needed to go to find_by_sql for this and would LOVE to stay
with ActiveRecord, instead.

Many thanks,


If the goal is to find a Post (or all Posts) including associated
Comments by a particular Person, you could stick with #find if you
moved the Comment-Person constraint to the WHERE clause, i.e.,

:include => [:author, :comments],
:conditions => [‘comments.person_id = ?’, x]



Thanks for your suggestion and time, John. It wasn’t exactl what we
were after, but luckily we did find it here:


Hope this helps someone else as well.