Eager include associated count?

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%>

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