Apply a new callback to existing records

Posted Over 13 years ago. Visible to the public.

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

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'
Henning Koch
Last edit
Over 13 years ago
Keywords
activerecord, rails, deploy
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2010-12-15 12:53)