Last updated

The migration that cannot be undone: Irreversible Migration

Migrations have up and down methods, as we all know. But in some cases, your up method does things you can’t undo in your down method.

For example:

1def self.up
2  # Change the zipcode from the current :integer to a :string type.
3  change_column :address, :zipcode, :string
4end

Now, converting integers to strings will always work. But, you feel it coming, converting a string into an integer will not always be possible. In other words, we can’t reverse this migration.

That’s why we should raise ActiveRecord::IrreversibleMigration in the down method.

1def self.down
2  raise ActiveRecord::IrreversibleMigration
3end

Now, if you run your migration (upwards), you’ll see it being applied like it shoud. However, if you try to go back, you’ll see rake aborting with ActiveRecord::IrreversibleMigration.

1$ rake db:migrate VERSION=4
2-- Database is migrated
3$ rake db:migrate VERSION=3
4-- Rake aborted!
5-- ActiveRecord::IrreversibleMigration

So, if you have things you can’t undo, raise ActiveRecord::IrreversibleMigration in your migration’s down method.

Tags: General