# Find :include causing n+1 queires

**URL:** <https://www.ruby-forum.com/t/find-include-causing-n-1-queires/168799>\
**Category:** Rails\
**Created:** [May 26, 2009, 7:33am UTC](https://www.ruby-forum.com/t/find-include-causing-n-1-queires/168799 "2009-05-26T07:33:00Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![timhunter](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/71e660/32.png) [@timhunter](https://www.ruby-forum.com/u/timhunter)\
**Post date:** [May 26, 2009, 7:33am UTC](https://www.ruby-forum.com/t/find-include-causing-n-1-queires/168799/1 "2009-05-26T07:33:00Z")

</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 => [:user, :users],
    :conditions => {:id=> ids},
    :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:** ![timhunter](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/71e660/32.png) [@timhunter](https://www.ruby-forum.com/u/timhunter)\
**Post date:** [May 26, 2009, 9:36am UTC](https://www.ruby-forum.com/t/find-include-causing-n-1-queires/168799/2 "2009-05-26T09:36:28Z")

</div>

On May 26, 6:32 am, Tim H. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> 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
