Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I rollback using change_column method in Rails 4 and above?

Is change_column method able to rollback when it is used in migrations in Rails 4 and above?

Here is an example:

def change
  change_column etc
end

Should I use up and down methods instead?

like image 633
Sidney Avatar asked Oct 21 '16 15:10

Sidney


People also ask

How do I rollback a particular migration in Rails?

i found these steps most useful. To check for status, run rails db:migrate:status . Then you'll have a good view of the migrations you want to remove. Then, run rails db:rollback to revert the changes one by one.

Which command is used to rollback migration in Rails?

You must rollback the migration (for example with bin/rails db:rollback ), edit your migration, and then run bin/rails db:migrate to run the corrected version.

How do I rollback a change column migration?

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.

How do you run down migration in Rails?

To run a specific migration up or down, use db:migrate:up or db:migrate:down . The version number in the above commands is the numeric prefix in the migration's filename. For example, to migrate to the migration 20160515085959_add_name_to_users. rb , you would use 20160515085959 as the version number.


1 Answers

change_column cannot be reverted by default. Rails cannot know the column definition before the migration, so it cannot roll back to this original definition.

Therefor starting with Rails 4, you can provide Rails with the necessary information. That's what the reversible method is for:

def change
  reversible do |dir|
    dir.up do
      change_column :users, :score, :decimal, precision: 6, scale: 2
    end
    dir.down do
      change_column :users, :score, :decimal, precision: 4, scale: 2
    end
  end
end

At first glance, this seems more complicated than using up and down. The advantage is, that you can mix it with reversible migrations.
If i.e. you add a bunch of fields to a table and have to change few fields along, you can use change_table and add_column together with reversible to have a clean and compact migration:

def change
  change_table :users do |t|
    t.string :address
    t.date :birthday
    # ...
  end

  reversible do |dir|
    dir.up do
      change_column :users, :score, :decimal, precision: 6, scale: 2
    end
    dir.down do
      change_column :users, :score, :decimal, precision: 4, scale: 2
    end
  end
end
like image 130
Martin M Avatar answered Oct 15 '22 00:10

Martin M