How to find the count of the associated models with less number of queries being executed?

I have a rails app where I need to take count of the associated model like post.comments.count and this loads up number of queries and I was searching for option to reduce this and found counter cache which saves the count in the table but is there any other option to find the count without saving in the table?

Thanks in advance.

The best solution i know to solve this issue with less number of queries is the counter_cache :wink:

http://guides.rubyonrails.org/association_basics.html#counter-cache

This is really simple, but surprisingly effective: If you already have post.comments, then call post.comments.length on it instead of post.comments.count on it and it won’t make another SELECT COUNT(*) query.

Otherwise, counter cache.

In case of counter cache, for example, how can I specify a condition to select the count of comments that I have marked as valid something like shown below

belongs_to :post, :counter_cache => true, :conditions => [“valid IS NOT NULL”]

You can supply the counter column name (apart from true) to the counter_cache option.

http://stackoverflow.com/a/7459476/1860178