Sometimes, data migrations are required. As time passes, code changes and migrations using your domain model are no longer valid and migrations fail. What are the best practices for migrating data?
I tried make an example to clarify the problem:
Consider this. You have a migration
class ChangeFromPartnerAppliedToAppliedAt < ActiveRecord::Migration
User.all.each do |user|
user.applied_at = user.partner_application_at
class AddAcceptanceConfirmedAt < ActiveRecord::Migration
add_column :users, :acceptance_confirmed_at, :datetime
class User < ActiveRecord::Base
An error has occurred, this and all later migrations canceled:
undefined method `acceptance_confirmed_at=' for #<User:0x007f85902346d8>
Best practice is: don't use models in migrations. Migrations change the way AR maps, so do not use them at all. Do it all with SQL. This way it will always work.
User.all.each do |user| user.applied_at = user.partner_application_at user.save end
I would do like this
update "UPDATE users SET applied_at=partner_application_at"