为什么我必须运行迁移两次才能使值出现在数据库中?

发布于 2024-08-28 13:03:01 字数 547 浏览 4 评论 0原文

令人费解的是,当我使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

别理我 2024-09-04 13:03:01

尝试

添加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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文