Rails回滚change_column迁移

Ume*_*tra 1 ruby-on-rails database-migration ruby-on-rails-4 ruby-on-rails-5

我只是迁移了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
Run Code Online (Sandbox Code Playgroud)

迁移之后,我意识到我还没有推送代码,因此理想情况下,我应该回滚直到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.
Run Code Online (Sandbox Code Playgroud)

我认为上述错误消息(以及互联网上的其他帖子)中建议的方法可以防止此问题,而可以解决(如果我错了,请纠正我)。现在如何回滚此迁移?

Vis*_*hal 5

您需要更新迁移文件代码。删除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
Run Code Online (Sandbox Code Playgroud)

在up方法中,写下您要执行的操作,例如将列数据类型更改为text,

在down方法中,如果您回滚迁移,则应该执行什么操作,例如当前您的列数据类型为string,并且您希望在回滚时将其回滚为string而不是编写适当的代码。