Skip to content

Instantly share code, notes, and snippets.

@bschaeffer
Last active February 23, 2021 19:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bschaeffer/873a3e0616b7efd142e6 to your computer and use it in GitHub Desktop.
Save bschaeffer/873a3e0616b7efd142e6 to your computer and use it in GitHub Desktop.
Mass update counter cache columns (with Rails references)
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
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