Rails won't let me change records during migra

2020-02-23 07:31发布

问题:

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

回答1:

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.



回答2:

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 


回答3:

If you combine the two in your initial migration like this, does that work?

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