Created
December 6, 2012 16:11
-
-
Save svyatov/4225663 to your computer and use it in GitHub Desktop.
Rails Rake Task: Update all cache counters
This file contains 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
desc 'Update all cache counters' | |
task :update_cache_counters => :environment do | |
models_to_update = {} | |
# or: Rails.application.eager_load! | |
# Dir loads less, so it's faster | |
Dir.glob(Rails.root.join('app/models/*')).each { |model| require model } | |
# as a convention, cache counter column name must begin with assotiacion's name and end with '_count' suffix, | |
# e.g. 'comments_count', 'posts_count' | |
ActiveRecord::Base.descendants.each do |model| | |
cache_counters = model.column_names.select { |n| n =~ /_count\z/ }.map { |n| n.gsub(/_count\z/, '').to_sym } | |
cache_counters.select! { |c| model.reflect_on_association(c) } # check if association is exists | |
models_to_update[model] = cache_counters if cache_counters.size > 0 | |
end | |
models_to_update.each do |model, counters| | |
model.select(:id).find_each do |record| | |
model.reset_counters record.id, *counters | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also https://www.krautcomputing.com/blog/2015/01/13/recalculate-counter-cache-columns-in-rails/