Read more

Apply a new callback to existing records

Henning Koch
December 15, 2010Software engineer at makandra GmbH

So you added a new callback to your model that (e.g.) caches some data when it is saved. Now you need to run that callback for the 10000 existing records in the production database. You have two options here:

  1. Write a clever migration, possibly by embedding the model into the migration script Show archive.org snapshot .
  2. Open the Rails console after deployment and re-save every single record. You should probably add two chores to Pivotal Tracker Show archive.org snapshot so you won't forget to do this on both staging and production.

Advice for re-saving many records

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

If you choose to re-save every record, try not to simply use save! because it also re-runs every single validation and other callback in the model. Although this should be save 99% of the time, it's also slow and tempting fate. Use this code instead to only run the new callback method and skip validations and other callbacks:

Model.all.each do |m|
  m.send(:new_callback_method)
  m.send(:update_without_callbacks)
end
'Done'
Posted by Henning Koch to makandra dev (2010-12-15 13:53)