# Eager loading has\_many through

**URL:** <https://www.ruby-forum.com/t/eager-loading-has-many-through/127512>\
**Category:** Rails\
**Created:** [January 29, 2008, 11:05pm UTC](https://www.ruby-forum.com/t/eager-loading-has-many-through/127512 "2008-01-29T23:05:50Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Tarscher](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/8491ac/32.png) [@Tarscher](https://www.ruby-forum.com/u/Tarscher)\
**Post date:** [January 29, 2008, 11:05pm UTC](https://www.ruby-forum.com/t/eager-loading-has-many-through/127512/1 "2008-01-29T23:05:50Z")

</div>

hi all,

My relationships:

- group habtm user and
- user has\_many events :through statistics.  
The statistics contains the id of user and is of event and additional  
data.

How can I get all the users in a group with their statistics via eager  
loading.

I tried:  
@users = a\_node.users.find(:all, :include =\> :statistics, :conditions  
=\> [“statistics.event\_id = ?”, event.id])

The problem is that I only get the users with a statistics record and  
I also want users without any stastics. I think the problem is caused  
by :conditions =\> [“statistics.event\_id = ?”, event.id] but I don’t  
know how to include the event\_id in another way.

Someone can help me out?

Thanks  
-Stijn

---

<div class="post-metadata">

**Author:** ![Tarscher](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/8491ac/32.png) [@Tarscher](https://www.ruby-forum.com/u/Tarscher)\
**Post date:** [January 30, 2008, 7:00am UTC](https://www.ruby-forum.com/t/eager-loading-has-many-through/127512/2 "2008-01-30T07:00:26Z")

</div>

> The problem is that I only get the users with a statistics record and  
> I also want users without any stastics. I think the problem is caused  
> by :conditions =\> [“statistics.event\_id = ?”, event.id] but I don’t  
> know how to include the event\_id in another way.
> 
> Someone can help me out?
> 
> Thanks  
> -Stijn

Try using the :joins parameter and manually join to the statistics table  
with an OUTER join, or use the find\_by\_sql method if you have to.

The joins param value will be something like :joins =\> “left outer join  
statistics s on s.user\_id = user.id”

Having the left outer join should still allow you to filter the the  
statistics with the event\_id and include the users with and without  
stats.
