Requirements I need to create a migration, for a live production database that does the following:
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
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.