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.

neurodynamic
  • 4,294
  • 3
  • 28
  • 39
  • 1
    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) – Frederick Cheung Dec 28 '15 at 18:40
  • 1
    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. – bjacobs Sep 07 '18 at 20:49
  • 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? – phil Feb 15 '19 at 16:07

1 Answers1

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

Community
  • 1
  • 1
elements
  • 1,047
  • 2
  • 9
  • 21
  • 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. – bjacobs Sep 07 '18 at 21:07