为什么我必须运行迁移两次才能使值出现在数据库中?
令人费解的是,当我使用 rake 运行以下迁移代码时,列(而不是值)出现在 MySQL 数据库表中:
class AddTypeToItems < ActiveRecord::Migration
def self.up
add_column :items, 'type', :string, :limit => 100, :null => false
Item.find_by_name('YUMMY_JUICE').update_attribute(:type, 'Juice')
Item.find_by_name('TASTY_JUICE').update_attribute(:type, 'Juice')
Item.find_by_name('NASTY_JUICE').update_attribute(:type, 'Juice')
end
def self.down
remove_column :items, 'type'
end
end
我实际上必须回滚迁移,然后再次运行它(总共两次)才能显示值。到底是怎么回事?
Inexplicably, when I run the following migration code using rake, the column, but not the values, appear in the MySQL DB table:
class AddTypeToItems < ActiveRecord::Migration
def self.up
add_column :items, 'type', :string, :limit => 100, :null => false
Item.find_by_name('YUMMY_JUICE').update_attribute(:type, 'Juice')
Item.find_by_name('TASTY_JUICE').update_attribute(:type, 'Juice')
Item.find_by_name('NASTY_JUICE').update_attribute(:type, 'Juice')
end
def self.down
remove_column :items, 'type'
end
end
I actually have to rollback the migration, then run it again (twice in total) for the values to appear. What is going on?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试
添加
Items.reset_column_information
在
add_column
语句后 。 ActiveRecord 会缓存列信息,因此在使用它们之前需要重新加载。Try adding
Items.reset_column_information
after your
add_column
statement. ActiveRecord caches the column info, so you need to reload before using them.