Counter cache not updating

Posted by / 21-Sep-2016 18:10

Although the mechanism built into Rails does the hard part, you still have to implement perform a couple of steps or else it won’t work at all.

Here are the steps you need to do to get a counter cache to behave.

There are quite a few tests that rely on this, where the model fixtures don't specify counter_cache explicitly.

Maybe someone smarter than me( @tenderlove) will have an idea to come around this. But if you have an instance of that model it won't know about this change and if you save it later it will increment the field again and causes the issue. On rails 4 the after_update code was also introduced https://github.com/rails/rails/blob/master/activerecord/lib/active_record/associations/builder/belongs_to.rb#L85 leading to this bug that now we call increment, on the for not updating the counter until the model is persisted. (post: post) assert_equal 1, post.reload.comments_count assert_equal nil, post2.reload.comments_count = post2 comment.save!

Used to cache the number of belonging objects on associations.

For example, a comments_count column in a Post class that has many instances of Comment will cache the number of existent comments for each post.

, the collection would be assumed to be loaded and and return an empty array.

Let’s start by using the same example as in the manual: we want to count the number of comments on the blog post.

counter cache not updating-25counter cache not updating-75counter cache not updating-17

The model definitions look like this: The only problem left is that the counts are off if there are already posts and comments in the database.

One thought on “counter cache not updating”