Created
March 20, 2016 09:37
-
-
Save dpaluy/22b4c0c699fb897f45ee to your computer and use it in GitHub Desktop.
Recalculate counter cache columns in Rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class CacheCounterService | |
| def initialize | |
| @id = SecureRandom.hex(6) | |
| end | |
| def call | |
| # Make sure to load all models first | |
| Rails.application.eager_load! | |
| ActiveRecord::Base.descendants.each do |many_class| | |
| many_class.reflections.each do |name, reflection| | |
| if reflection.options[:counter_cache] | |
| one_class = reflection.class_name.constantize | |
| one_table, many_table = [one_class, many_class].map(&:table_name) | |
| ids = one_class | |
| .joins(many_table.to_sym) | |
| .group("#{one_table}.id") | |
| .having("#{one_table}.#{many_table}_count != COUNT(#{many_table}.id)") | |
| .pluck("#{one_table}.id") | |
| ids.each do |id| | |
| one_class.reset_counters id, many_table | |
| end | |
| end | |
| end | |
| end | |
| end | |
| end |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Source: https://www.krautcomputing.com/blog/2015/01/13/recalculate-counter-cache-columns-in-rails/