This must be something simple but it's driving me nuts!
I have a migration where I want to update a record afterward
class SubjectsTextField < ActiveRecord::Migration
def self.up
add_column :users, :subjects, :text
User.find(39).update_attribute :subjects, "hey there"
end
def self.down
remove_column :users, :subjects
end
end
The column gets created but when I go to check record 39, it's subjects field is null and doesn't say "hey there". No errors are thrown during the migration and the update_attribute line returns true as if it had worked.
This line works perfectly in the console and has the expected effect:
User.find(39).update_attribute :subjects, "hey there"
I tried putting the update_attribute line in a second migration. If I blow through both of them in one "rake db:migrate" all the way to current, it still doesn't work.
But here is the weird part. If I run two separate migrations, say "rake db:migrate VERSION=10" to only create the column and then the second one with "rake db:migrate" to update the attribute IT WORKS!
What the heck is going on...how do I modify a record during a migration? I seem to remember doing this quite often in the past. Maybe it is something different with Rails 2.3.2?
Thanks! Brian
You need to call reset_column_information
on the model you changed before you can use the new column. Add this between the add_column
and update:
User.reset_column_information
See "Using a model after changing its table" on the ActiveRecord::Migration page.
This syntax is much clear...try with change_table
class AddReceiveNewsletterToUsers < ActiveRecord::Migration
def self.up
change_table :users do |t|
add_column :users, :subjects, :text
end
User.find(39).update_attribute "subjects", "hey there"
end
def self.down
remove_column :users, :receive_newsletter
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With