首页 > 解决方案 > 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.

我认为上述错误消息(以及互联网上的其他帖子)中建议的方法是对这个问题的预防,而不是治疗(如果我错了,请纠正我)。我现在如何回滚此迁移?

标签: ruby-on-railsruby-on-rails-4ruby-on-rails-5database-migration

解决方案


您需要更新迁移文件代码。删除 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 方法中,如果您回滚迁移,它应该做什么,例如当前您的列数据类型是字符串,并且您希望在回滚时将其恢复为字符串,而不是编写适当的代码。


推荐阅读