Last active
February 23, 2021 19:35
-
-
Save bschaeffer/873a3e0616b7efd142e6 to your computer and use it in GitHub Desktop.
Mass update counter cache columns (with Rails references)
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 UpdateCounters < ActiveRecord::Migration | |
def up | |
say_with_time 'Updating counter_cache_column for ModelWithColumn' do | |
ActiveRecord::Base.connection.execute <<-SQL | |
UPDATE model_with_column | |
SET counter_cache_column = ( | |
SELECT COUNT(*) | |
FROM model_with_counter_cache | |
WHERE model_with_counter_cache.reference = model_with_column.id | |
) | |
SQL | |
end | |
end | |
end |
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
UPDATE model_with_column | |
SET counter_cache_column = ( | |
SELECT COUNT(*) | |
FROM model_with_counter_cache | |
WHERE model_with_counter_cache.reference = model_with_column.id | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment