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 %> <td><%= user.first_name + " " + user.last_name %></td> <%= user.stores.count %></td> <% end%> --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---
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 --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---