2009-06-09 77 views
16

這一定很簡單,但它讓我瘋狂!
我有一個移民,我想更新之後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

回答

33

嘗試你需要調用reset_column_information你改變之前,你可以使用新列模型。添加這個add_column和更新之間:

User.reset_column_information 

ActiveRecord::Migration頁上的「改變其表後使用模型」。

+0

這是感謝邁克爾!不能相信我從來沒有遇到過......感謝一百萬。 – 2009-06-09 22:29:50

0

如果您在初始遷移時將這兩者結合起來,這是否奏效?

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

1

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