Rails 4 counter cache out of sync
Asked Answered
R

1

8

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.

Regality answered 28/12, 2015 at 17:27 Comment(3)
You need to reproduce the circumstances that first cause it to go wrong. Once it's gone wrong there's nothing you can do (other than update the counter manually)Baking
Did you ever figure out the answer to this? I'm seeing the same thing where the model_count is HIGHER than the model.count. Not sure how that can happen. A reset does work, but doesn't fix the root issue of it getting out of sync in the first place.Benison
I am 'me too'ing this because we are seeing this as well. We are never (ok, rarely) destroying. I am wondering if it is failing on failed creates?Dickdicken
G
8

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

Glucinum answered 28/12, 2015 at 19:42 Comment(1)
But how would it go out of sync in the first place? And how would the model_count go HIGHER than the model.count? Assuming you are not doing any deleting, destroying, or moving.Benison

© 2022 - 2024 — McMap. All rights reserved.