Can I rollback using change_column method in Rails 4 and above?
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