# Extending left outer joins when using active eager loading

**URL:** <https://www.ruby-forum.com/t/extending-left-outer-joins-when-using-active-eager-loading/106977>\
**Category:** Rails\
**Created:** [June 16, 2007, 12:15am UTC](https://www.ruby-forum.com/t/extending-left-outer-joins-when-using-active-eager-loading/106977 "2007-06-16T00:15:55Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [June 16, 2007, 12:15am UTC](https://www.ruby-forum.com/t/extending-left-outer-joins-when-using-active-eager-loading/106977/1 "2007-06-16T00:15:55Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [June 16, 2007, 7:19pm UTC](https://www.ruby-forum.com/t/extending-left-outer-joins-when-using-active-eager-loading/106977/2 "2007-06-16T19:19:13Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [June 20, 2007, 12:05am UTC](https://www.ruby-forum.com/t/extending-left-outer-joins-when-using-active-eager-loading/106977/3 "2007-06-20T00:05:46Z")

</div>

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](http://www.ruby-forum.com/topic/82400#261410)

Hope this helps someone else as well.

Cheers!
