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
post.comments.count and this loads up number of queries and I was
for option to reduce this and found counter cache which saves the count
the table but is there any other option to find the count without saving
the table?

Thanks in advance.

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

El jueves, 6 de noviembre de 2014 07:40:42 UTC+1, Logesh m escribió:

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(*)

Otherwise, counter cache.

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

El viernes, 7 de noviembre de 2014 07:20:32 UTC+1, Logesh m escribió:

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