Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 counter cache out of sync

I have a Rails 4.2 app with a counter cache (setup with belongs_to :my_model, counter_cache: true) that is setting incorrect values. I can literally call up the console and call MyModel.associated_model_count and get 20, and then call MyModel.associated_model.count and get 19. Saving the model does not fix this.

The values don't seem to be off by much, but some are definitely off and I can't figure out why.

like image 434
neurodynamic Avatar asked Dec 28 '15 17:12

neurodynamic


1 Answers

To answer part of your question and hopefully help you in debugging, the counter column is only updated on create and destroy, so saving the object wouldn't trigger a counter update. More detail can be found under the :counter_cache entry under Options here: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-belongs_to

You can manually trigger a counter update using MyModel.reset_counters(id, *counters) (http://apidock.com/rails/ActiveRecord/CounterCache/reset_counters) if you want to get to a clean state in order to pinpoint where it goes off.

Related question with helpful answers and discussion: Rails counter_cache not updating correctly

like image 120
elements Avatar answered Nov 07 '22 22:11

elements