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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With