我添加了两个迁移,在第一个迁移中,我在模型中添加了一个列,在第二个迁移中,我执行了一个将值存储在最近添加到一些行中的列中的函数。
问题是,当我运行rake db:迁移时,第二个迁移会引发错误,因为第一个迁移已加载,但数据库尚未更改,因此一种方法是两次运行命令(它可以使用)。<<<<<<<<<<<<<<<</p>
第一次迁移:
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 =
请注意,该方法未定义是前面添加的属性的名称。
我想知道是否有一种方法可以避免两次命令而不会丢任何错误。
更新:
我使用 reset_column_information 方法找到了一个解决方案方法,该方法会在下一个请求中重新加载列。
重置有关列的所有缓存信息,这将使它们在下一个请求中重新加载。
此方法最常见的用法模式可能是在迁移中,当创建表之后,您想用一些默认值
填充它。
更多信息:链接
为什么不在一次迁移中全部进行?
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