Rails不会让我在迁移过程中更改记录

问题描述:

这一定很简单,但它让我疯狂!
我有一个移民,我想更新之后Rails不会让我在迁移过程中更改记录

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 

列被创造了一项纪录,但是当我去检查记录39,它的主题字段为空,不说“嘿”。迁移过程中不会引发任何错误,并且update_attribute行将返回true,就像它已经工作一样。

此行完全在控制台和具有预期的效果:

User.find(39).update_attribute :subjects, "hey there" 

我试图把update_attribute线在第二迁移。如果我通过一个“rake db:migrate”一路通过它们到最新,它仍然不起作用。

但是这里是奇怪的部分。如果我运行两个单独的迁移,比如说“rake db:migrate VERSION = 10”,只创建列,然后用“rake db:migrate”更新属性IT WORKS!

到底发生了什么......如何在迁移过程中修改记录?我似乎记得过去经常这样做。也许它与Rails 2.3.2有所不同?

谢谢! Brian

尝试你需要调用reset_column_information你改变之前,你可以使用新列模型。添加这个add_column和更新之间:

User.reset_column_information 

ActiveRecord::Migration页上的“改变其表后使用模型”。

+0

这是感谢迈克尔!不能相信我从来没有遇到过......感谢一百万。 – 2009-06-09 22:29:50

如果您在初始迁移时将这两者结合起来,这是否奏效?

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 
+0

不能用这种方式工作与报价,谢谢你的回应! – 2009-06-09 22:25:28

这句法是非常清楚......与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