Andrii Furmanets
Andrii Furmanets

Reputation: 1161

How does update counter_cache when we run raw SQL?

I've got few counter caches which update when model save/update or destroy because of after hook. If I create/update or destroy record using raw SQL, how can I update counter cache automatically?

Upvotes: 0

Views: 571

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230481

This should help you

http://apidock.com/rails/ActiveRecord/CounterCache/ClassMethods/reset_counters

# For Post with id #1 records reset the comments_count
Post.reset_counters(1, :comments)

Resets one or more counter caches to their correct value using an SQL count query. This is useful when adding new counter caches, or if the counter has been corrupted or modified directly by SQL.

Upvotes: 2

Related Questions