Reputation: 3516
I'm splitting out some data from a model into a new one and creating an association between them.
I've added the new_model_id
to OldModel
, created NewModel
with address
as a string attribute, and have the following migrations:
class RemoveAddressFromOldModel < ActiveRecord::Migration
def up
OldModel.where("address IS NOT NULL AND address != ''").each do |i|
j = NewModel.create(address: i.address)
i.new_model_id = j.id
i.save
end
remove_column :old_models, :address
end
def down
add_column :old_models, :address, :string
end
end
While the NewModel.create
is working perfectly and getting the right data, the i.save
doesn't seem to be working, as old_models.new_model_id
isn't being populated.
What am I missing with this?
Upvotes: 0
Views: 85
Reputation: 11520
This sounds like validations failing to me, though it could also be a before_* callback that's preventing the save. I can't speculate further without the OldModel code.
Call save
when you expect it to fail and you plan to check the return value; call save!
when you expect it to succeed want an exception instead. I'd use save!
here because I would want the migration to fail if the save fails.
Also: your migration copies data from OldModel to NewModel in up
, but doesn't copy it the other way in down
. In this configuration, rake db:migrate:redo
would succeed but silently discard information. If this information is important to you, I'd recommend either a) making the migration bidirectional by copying the data back or b) removing down
so Rails knows it can't un-do.
Upvotes: 2