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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With