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
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.