devroom.io/content/posts/2008/2008-05-06-the-migration-that-cannot-be-undone-irreversible-migration.md

41 lines
1.2 KiB
Markdown
Raw Normal View History

2015-03-26 11:28:08 +00:00
+++
date = "2008-05-06"
title = "The migration that cannot be undone: Irreversible Migration"
tags = ["General"]
slug = "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:
2024-01-30 08:26:51 +00:00
```ruby
def self.up
2015-03-26 11:28:08 +00:00
# Change the zipcode from the current :integer to a :string type.
change_column :address, :zipcode, :string
2024-01-30 08:26:51 +00:00
end
```
2015-03-26 11:28:08 +00:00
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.
2024-01-30 08:26:51 +00:00
```ruby
def self.down
2015-03-26 11:28:08 +00:00
raise ActiveRecord::IrreversibleMigration
2024-01-30 08:26:51 +00:00
end
```
2015-03-26 11:28:08 +00:00
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.
2024-01-30 08:26:51 +00:00
```sh
$ rake db:migrate VERSION=4
2015-03-26 11:28:08 +00:00
-- Database is migrated
$ rake db:migrate VERSION=3
-- Rake aborted!
2024-01-30 08:26:51 +00:00
-- ActiveRecord::IrreversibleMigration
```
2015-03-26 11:28:08 +00:00
So, if you have things you can't undo, raise ActiveRecord::IrreversibleMigration in your migration's down method.