Rails 回滚 change_column 迁移

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

迁移完成后,我意识到我没有推送我的代码,所以理想情况下我应该回滚到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.

我认为上面的错误信息(以及互联网上的其他帖子)中提出的方法是预防这个问题的措施,而不是治疗方法(如果我说错了,请纠正我)。现在我该如何回滚此次迁移呢?

1个回答

14

你需要更新迁移文件代码。删除def change方法,并添加up和down两个方法,因为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 方法中编写如果要回滚迁移应该执行什么操作,比如当前你的列数据类型为字符串,当你回滚时想要将其还原为字符串,则编写相应的代码。


1
谢谢,完美的解决方案。 - Umesh Malhotra
1
@UmeshMalhotra 请接受这个答案,它将帮助其他用户解决他们的问题 :) - Vishal
我遇到了这个错误:- PG :: DatatypeMismatch:ERROR:无法自动将列“phone_no_1”转换为整数类型 提示:您可能需要指定“USING phone_no_1 :: integer”。 :ALTER TABLE“suppliers” ALTER COLUMN“phone_no_1” TYPE integer - Umesh Malhotra
这个可行。def down 执行 'ALTER TABLE suppliers ALTER COLUMN phone_no_1 TYPE text USING (phone_no_1::integer)' 执行 'ALTER TABLE suppliers ALTER COLUMN phone_no_2 TYPE text USING (phone_no_2::integer)' end - Umesh Malhotra
是的,很高兴听到这个 :) - Vishal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接