Extending left outer joins when using active eager loading

Hi,

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

“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,

J

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.,

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

-John

Hi,

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

http://www.ruby-forum.com/topic/82400#261410

Hope this helps someone else as well.

Cheers!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs