# Eager include associated count?

**URL:** <https://www.ruby-forum.com/t/eager-include-associated-count/127880>\
**Category:** Rails\
**Created:** [February 2, 2008, 1:50am UTC](https://www.ruby-forum.com/t/eager-include-associated-count/127880 "2008-02-02T01:50:50Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![wheels](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/7bcc69/32.png) [@wheels](https://www.ruby-forum.com/u/wheels)\
**Post date:** [February 2, 2008, 1:50am UTC](https://www.ruby-forum.com/t/eager-include-associated-count/127880/1 "2008-02-02T01:50:50Z")

</div>

So I know you can eager include associated rows with the :include, but  
is there a way to include just the associated count?

User.find(:all, :select =\> ‘id, first\_name, last\_name,  
created\_at’, :limit =\> 30)  
I want to include user.store.count in the above query.

Right now, this gives me an n+1 queries because i get the count for  
each row.

\<% for user in @users %\>

\<%= user.first\_name + " " + user.last\_name %\> \<%= user.stores.count %\> \<% end%\>

---

<div class="post-metadata">

**Author:** ![wheels](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/7bcc69/32.png) [@wheels](https://www.ruby-forum.com/u/wheels)\
**Post date:** [February 2, 2008, 7:27am UTC](https://www.ruby-forum.com/t/eager-include-associated-count/127880/2 "2008-02-02T07:27:04Z")

</div>

The count method is not a bad solution. It’s straight forward and  
count queries are very fast.

Here’s a single query way to do it:  
User.find(:all, :limit =\> 30, :include =\> :stores)  
Then call \<%= user.length %\> from the view. Downside is that you are  
loading all the stores into memory. On a side note I would recommend  
staying away from using the :select option with find. Using :select  
cripples the returned objects, any fields you did not include can not  
be accessed. Also, I don’t think you can combine :select  
with :include.

If you are concerned about performance take a look at the belongs\_to  
couter\_cache. All you have to do is add a stores\_count column to your  
User model and put this line in your Store model:  
belongs\_to :user, :counter\_cache =\> true  
Whenever you add/delete a store the stores\_count will be updated  
automatically. So you don’t have to include/join any tables in the  
query:  
User.find(:all, :limit =\> 30)  
\<%= user.stores\_count %\>

Aaron
