【问题标题】:Modifying migration column not loaded in migration rails修改迁移轨道中未加载的迁移列
【发布时间】:2017-04-27 09:31:20
【问题描述】:

我添加了两个迁移,在第一个迁移中,我向模型添加一列,在第二个迁移中,我执行一个函数,将值存储到最近添加的某些行的列中。

问题是,当我运行 rake db:migrate 时,第二次迁移会引发错误,因为第一次迁移已加载但数据库尚未更改,因此一种方法是运行该命令两次(它有效)。

第一次迁移:

class AddRegisteredReportToSpecialOfferUse < ActiveRecord::Migration
  def up
    add_column :special_offer_uses, :registered_report, :boolean, default: false
  end

  def down
    remove_column :special_offer_uses, :registered_report
  end
end

第二次迁移:

class CreateReportsFromMigrations < ActiveRecord::Migration
  def change
    OneClass.perform
  end
end

OneClass.perform 是一种更新之前添加的属性的方法

def perform
´´´
special_offer_uses.update_attribute(:registered_report, true)
´´´
end

抛出的错误:

StandardError:发生错误,所有后续迁移均已取消: 未定义的方法`registered_report=

注意,方法undefined是之前添加的属性名。

我想知道是否有办法避免运行两次命令而不会抛出任何错误。

更新:

我找到了一个使用 reset_column_information 方法的解决方案,该方法会导致在下一次请求时重新加载列。

重置有关列的所有缓存信息,这将导致它们在下一次请求时重新加载。

此方法最常见的使用模式可能是在迁移中,即在创建表后您想用一些默认值填充它

更多信息:link

【问题讨论】:

  • 你能显示error消息吗?
  • 我从来没有遇到过这个问题。我什至在同一次迁移中这样做
  • 你能把2个迁移和错误信息放在一起
  • 我添加了错误以及迁移。让我知道我是否清楚。
  • 为什么special_offer_uses后面有一个空格,好像你想把新列设置为true对吗?

标签: ruby-on-rails ruby database-migration


【解决方案1】:

为什么不一次迁移全部完成?

class AddRegisteredReportToSpecialOfferUse < ActiveRecord::Migration
  def up
    add_column :special_offer_uses, :registered_report, :boolean, default: false
    OneClass.perform
  end

  def down
    remove_column :special_offer_uses, :registered_report
  end
end

【讨论】:

  • 这是一个可能的解决方案。但是我正在寻找解决问题的方法
  • 如果您坚持要进行第二次迁移,请尝试使用up 方法而不是change
猜你喜欢
  • 2014-06-07
  • 2011-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-02
  • 2017-10-03
  • 1970-01-01
相关资源
最近更新 更多