Alvaro Alday
Alvaro Alday

Reputation: 363

How to stop a migration if a validation is false?

Requirements I need to create a migration, for a live production database that does the following:

  1. For each company verify if a set of names are instances of an utterance class associated with it.
  2. If said validation doesn't exist have the validation fail and return an error.
  3. If not continue migrating

Current behaviour I tried this:

class AddFeature < ActiveRecord::Migration[5.1]
  def change
    run_migration = true
    Company.all.each do |organization|
      Company.product_types_names.each { |type| run_migration &= Utterance.exists?("utter_#{type.to_s}", organization.id) }
    end

    if run_migration
      # my code
    end
  end
end

Although the changes to the database, don't occur I need the migration to stop with an error. Currently, the migration isn't stopped by any form of error when I an utterance doesn't exist.

Expected behavior

I would like to know how to simply return an error and stop the migration when one any of the instances don't exist. Something like this:

class AddFeature < ActiveRecord::Migration[5.1]
  def change
    Company.all.each do |organization|
      Company.product_types_names.each { |type| run_migration &= Utterance.exists?("utter_#{type.to_s}", organization.id) }
      # return_errors_and stop the app if validation false
    end

    # my code
  end
end

Upvotes: 1

Views: 994

Answers (1)

Ilya Konyukhov
Ilya Konyukhov

Reputation: 2791

Generally speaking, it is not recommended to write your custom code in Rails migrations. Migrations are for manipulations on database schema. You manipulate on data.

Answering your question: you can simply stop your migration by raising an exception, such as:

raise StandardError, "Invalid data"

In this case the migration will be stopped and not marked as completed (migration version won't be saved to schema_migrations table in your database). On next call of rake db:migrate it will try to run that migration again.

Upvotes: 5

Related Questions