pjmorse
pjmorse

Reputation: 9294

How should I *intentionally* stop a migration?

I have a migration to run, but before it runs I want to verify certain conditions (i.e. the migration calls an instance method on a model, and I want to ensure that the method exists before running the migration).

With that in mind, I can't find any documentation explaining how to stop the migration if the verification doesn't pass. It seems most likely that raising an exception is the smart way to do this. I found ActiveRecord::Rollback which looks like a good candidate, because it explicitly rolls back a transaction, but it also has the characteristic of not re-raising once the transaction is rolled back, so I probably won't see any messages I attach to the exception.

I've been searching things like "rails cancel migration" but all the results seem to deal with migrations which have been unintentionally canceled. I want to fail intentionally (and gracefully) in certain conditions instead.

Upvotes: 3

Views: 2031

Answers (2)

pjmorse
pjmorse

Reputation: 9294

What I ended up doing was actually raise Exception, because ActiveRecord::Rollback would count the migration as completed and not allow for it to be re-run after fixing the error.

Upvotes: 1

Kieran Andrews
Kieran Andrews

Reputation: 5885

If you raise an exception inside of a migration, it will stop the migration.

Depending on what you need you could also try creating an interactive migration:

puts "*** What would you like to do? ***"
puts "(a)dd columns AND copy data"
puts "(c)olumns only (no data copying)"
puts "(d)ata only (no column adding)"
puts "(q)uit"
reply = $stdin.gets.chomp

Or just putting a if confidition inside your migration and only running the commands based on a state. The migration will still complete but the operations will not run.

Upvotes: 0

Related Questions