The counter cache for belongs_to associations is a useful Rails feature to speed up your application. It allows to cache the number of objects which belong to the associated class. All you need to do is to add :counter_cache => true to the belongs_to association:

class Comment
  belongs_to :post, :counter_cache => true

And you need to add a column named “#{table_name}_count” (such as comments_count for a belonging Comment class) to the table which is associated with the “owning” class (such as a Post class). Now, the counter may have a wrong value for various reasons during development, for example if you add this column to an already existing system with a migration. In this case, you can correct the value with

UPDATE posts p SET comments_count = (SELECT Count(*) FROM comments c WHERE c.post_id =;

P.S. Another reason why counter-cache columns may have the wrong value is a bug if you use :dependent => :delete_all instead of :dependent => :destroy. For example a user has many comments (User has_many => :comments, :dependent => delete_all), and if the user is deleted, the comments are deleted, too, but the counter_cache columns are not updated.

About these ads