为什么我必须运行两次迁移才能在DB中显示值?

时间:2010-04-07 19:38:49

标签: mysql ruby-on-rails migration

令人费解的是,当我使用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

我实际上必须回滚迁移,然后再次运行它(总共两次)以显示值。发生了什么事?

1 个答案:

答案 0 :(得分:6)

尝试添加

Items.reset_column_information

在您的add_column声明之后

。 ActiveRecord缓存列信息,因此您需要在使用它们之前重新加载。