ruby-on-rails - Rails 回滚 change_column 迁移
问题描述
我刚刚迁移了我的 create_supplier 迁移,然后我意识到我的一种数据类型是错误的,所以我添加了另一个迁移,如下所示:-
class ChangePhoneToStringInSuppliers < ActiveRecord::Migration[5.1]
def change
change_column :suppliers, :phone_no_1, :string
change_column :suppliers, :phone_no_2, :string
end
end
迁移后,我意识到我没有推送我的代码,所以理想情况下我应该回滚到 create_suppliers 迁移并在那里自己添加更改。当我回滚 ChangePhoneToStringInSuppliers 时,我收到以下错误:-
This migration uses change_column, which is not automatically reversible.
To make the migration reversible you can either:
1. Define #up and #down methods in place of the #change method.
2. Use the #reversible method to define reversible behavior.
我认为上述错误消息(以及互联网上的其他帖子)中建议的方法是对这个问题的预防,而不是治疗(如果我错了,请纠正我)。我现在如何回滚此迁移?
解决方案
您需要更新迁移文件代码。删除 def 更改方法,而是向上和向下添加两种方法,因为 change_column 迁移不支持回滚。
我不知道您之前使用的是哪种列数据类型,所以请根据您的需要更改它
class ChangePhoneToStringInSuppliers < ActiveRecord::Migration[5.1]
def up
change_column :suppliers, :phone_no_1, :string
change_column :suppliers, :phone_no_2, :string
end
def down
change_column :suppliers, :phone_no_1, :text
change_column :suppliers, :phone_no_2, :text
end
end
在 up 方法中写下你想要做的事情,比如将列数据类型更改为文本,
在 down 方法中,如果您回滚迁移,它应该做什么,例如当前您的列数据类型是字符串,并且您希望在回滚时将其恢复为字符串,而不是编写适当的代码。
推荐阅读
- javascript - 除非所述字符串的一部分被Node中的特定字符包围,否则如何从字符串中删除所有空格?
- webrtc - 我可以将 IP 网络摄像机模拟为 Chromium 检测到的媒体设备吗?
- flutter - http post请求颤动
- php - 如何更新 JSON 文件中的特定 JSON 对象数组?
- php - Laravel - 在运行时停止发送电子邮件
- reactjs - 使用它来存储 JSX 组件以在其他地方显示是否是滥用上下文?
- json - Firestore json数据到带有颤动的列表视图
- regex - 消息框弹出两次(正则表达式)
- python - 将镶木地板转换为 csv 文件
- jquery - 为什么 $(document).width() 在 jQuery 中不起作用?