# find :include causing n+1 queires

**URL:** <https://discuss.rubyonrails.org/t/find-include-causing-n-1-queires/42854>\
**Category:** rubyonrails-talk\
**Created:** [May 26, 2009, 5:32am UTC](https://discuss.rubyonrails.org/t/find-include-causing-n-1-queires/42854 "2009-05-26T05:32:14Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Tim\_Haines](https://avatars.discourse-cdn.com/v4/letter/t/cdc98d/32.png) [@Tim\_Haines](https://discuss.rubyonrails.org/u/Tim_Haines)\
**Post date:** [May 26, 2009, 5:32am UTC](https://discuss.rubyonrails.org/t/find-include-causing-n-1-queires/42854/1 "2009-05-26T05:32:14Z")

</div>

Hey guys,

I just noticed one of my find calls is creating n+1 queries to be run. The find looks like this:

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Class.find(:all, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:include =\> [:user, :users], &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:conditions =\> {:id=\> ids}, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:order =\> order )

This is on Rails 2.3.2.

First the class is queried, then the join table between class and users, and then each user in the users collection is queried individually. If I remove the :users from the include, then the users aren't loaded (until I hit them in the view).

I thought the whole point of :include is to avoid the n + 1 scenario?

Cheers,

Tim.

---

<div class="post-metadata">

**Author:** ![Frederick\_Cheung](https://sea2.discourse-cdn.com/rubyonrails/user_avatar/discuss.rubyonrails.org/frederick_cheung/32/3901_2.png) [@Frederick\_Cheung](https://discuss.rubyonrails.org/u/Frederick_Cheung)\
**Post date:** [May 26, 2009, 7:35am UTC](https://discuss.rubyonrails.org/t/find-include-causing-n-1-queires/42854/2 "2009-05-26T07:35:25Z")

</div>

> Hey guys,
> 
> I just noticed one of my find calls is creating n+1 queries to be run. The find looks like this:
> 
> ```
> Class\.find\(:all,
> :include =&gt; \[:user, :users\],
> :conditions =&gt; \{:id=&gt; ids\},
> :order =&gt; order \)
> 
> ```
> 
> This is on Rails 2.3.2.
> 
> First the class is queried, then the join table between class and users, and then each user in the users collection is queried individually. If I remove the :users from the include, then the users aren't loaded (until I hit them in the view).
> 
> I thought the whole point of :include is to avoid the n + 1 scenario?

You should get one query per association loaded. If you are getting more than that then you are probably accidentally loading an association again. (for example be aware that the :include doesn't affect the association in the other direction). (I assume that in your actual app Class is called something else - you may run into strange problems if you try and override the core class Class with your own)

Fred
