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?
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.
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”]