Skip to content

Instantly share code, notes, and snippets.

@dpaluy
Created March 20, 2016 09:37
Show Gist options
  • Select an option

  • Save dpaluy/22b4c0c699fb897f45ee to your computer and use it in GitHub Desktop.

Select an option

Save dpaluy/22b4c0c699fb897f45ee to your computer and use it in GitHub Desktop.
Recalculate counter cache columns in Rails
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
@dpaluy
Copy link
Author

dpaluy commented Mar 20, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment