3

The migration that cannot be undone: Irreversible Migration

 3 years ago
source link: https://www.devroom.io/2008/05/06/the-migration-that-cannot-be-undone-irreversible-migration/?utm_campaign=Feed%3A+ariejan+%28ariejan%7Cdevroom.io%29
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

The migration that cannot be undone: Irreversible Migration

Posted: 2008-05-06 - Last updated: 2019-06-05

Tagged general

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:

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

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.

def self.down
  raise ActiveRecord::IrreversibleMigration
end

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.

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

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK