Rails 回滚 change_column 迁移

Rails rollback change_column migration

我刚刚迁移了我的 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_supplier 迁移并在其中添加更改。当我回滚 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 方法中写如果你回滚迁移它应该做什么,比如当前你的列数据类型是字符串并且你希望在回滚时将它恢复为字符串而不是编写适当的代码。