Rails rollback change_column migration
Asked Answered
E

1

7

I just migrated my create_supplier migration, then I realized that one of my data type was wrong, so I added another migration which looks like this:-

class ChangePhoneToStringInSuppliers < ActiveRecord::Migration[5.1]
  def change
    change_column :suppliers, :phone_no_1, :string
    change_column :suppliers, :phone_no_2, :string
  end
end

After migrating this, I realized that I haven`t pushed my code, so ideally I should rollback till create_suppliers migration and add the changes there itself. When I rollback ChangePhoneToStringInSuppliers, I get following error:-

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.

I think the method suggested in above error message(and other posts on internet) is a prevention to this problem, rather cure(correct me if I am wrong). How can I rollback this migration now?

Emmanuelemmeline answered 22/5, 2018 at 4:16 Comment(0)
U
16

you need to update migration file code. remove def change method and instead add both method up and down because change_column migration not supported rollback.

I don't know which column data type you used earlier, so please change it as per your need

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

In up method write what you want to do, like change column data type to text,

In down method write if you rollback migration what should it do, like currently your column data type is string and you want back it to string when you rollback than write appropriate code.

Uncommunicative answered 22/5, 2018 at 4:23 Comment(5)
Thanks, perfect solution.Emmanuelemmeline
@UmeshMalhotra Please accept this answer, it will help other users resolve their problem :)Uncommunicative
I am getting this error:- PG::DatatypeMismatch: ERROR: column "phone_no_1" cannot be cast automatically to type integer HINT: You might need to specify "USING phone_no_1::integer". : ALTER TABLE "suppliers" ALTER COLUMN "phone_no_1" TYPE integerEmmanuelemmeline
This worked def down execute 'ALTER TABLE suppliers ALTER COLUMN phone_no_1 TYPE text USING (phone_no_1::integer)' execute 'ALTER TABLE suppliers ALTER COLUMN phone_no_2 TYPE text USING (phone_no_2::integer)' endEmmanuelemmeline
Yes. glad to hear that :)Uncommunicative

© 2022 - 2024 — McMap. All rights reserved.