Search code examples
ruby-on-railscounter-cacheafter-create

counter_cache is stale in after_create hook


I rely on a counter cache value in an after_create hook of my model. However, my hook is called before the counter cache gets updated, thus breaking a computation.

Is there any way to force a counter cache "flush" so that I always see an up-to-date value in after_create?


Solution

  • Make sure your after_create :callback statement is after the has_many/belongs_to definition.

    If it doesn't work, you can create your own counter cache (it's nothing more than a call to increment/decrement, see add_counter_cache_callbacks) and ensure it's called before your code.