Last active
December 10, 2019 07:04
-
-
Save dapi/3349676 to your computer and use it in GitHub Desktop.
Update all model`s 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
# -*- coding: utf-8 -*- | |
# | |
namespace :db do | |
desc 'Update all model`s counters' | |
task :reset_counters => :environment do | |
Dir.glob(Rails.root + '/app/models/*.rb').each { |file| require file } | |
models = Rails::VERSION::MAJOR >= 3 ? ActiveRecord::Base.connection.tables.map {|t| t.classify.constantize rescue nil}.compact : Object.subclasses_of(ActiveRecord::Base) | |
models.each do |model| | |
countables = [] | |
model.reflections.keys.each do |reflection| | |
countables << reflection if model.attribute_names.include? "#{reflection.to_s}_count" | |
end | |
next if countables.empty? | |
puts "#{model}: #{countables.join(', ')}" | |
model.find_each do |r| | |
model.reset_counters r.id, *countables | |
end | |
end | |
end | |
end | |
# Alternative: | |
# https://github.com/rails/rails/blob/39d461703361834c2e51dd9179afce0f8a0a83ff/activerecord/lib/active_record/counter_cache.rb#L17 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment