Is there a way to know that a migration is running?

Multi tool use
Is there a way to know that a migration is running?
I have a model and I want to "register" meta-data about the columns, e.g. a label, description, in an initializer.
As part of this I want to check the column actually exists and raise if not.
However the column will not exist until the migration to add the column has been run.
Therefore I wish to skip this check if the environment is being initalized for the purposes of a migration.
Is there a way to know that a migration is running? Or that the db:migrate
rake task triggered the loading of the environment...
db:migrate
class Preferences < ActiveRecord::Base
def self.register(attrs)
raise if migration_not_running? && !column_names.include?(attrs.fetch(:column_name))
@schema << atrs
end
def self.schema
@schema ||=
end
private
def self.migration_not_running?
# ...?
end
end
1 Answer
1
What about checking if there are pending migrations, like the server does, when you try to load the views.
There's ActiveRecord::Migration.check_pending!, which raises ActiveRecord::PendingMigrationError
if there are ones. But it uses connection.migration_context.needs_migration?
logic under the hood, so it can be checked just like:
ActiveRecord::PendingMigrationError
connection.migration_context.needs_migration?
ActiveRecord::Base.connection.migration_context.needs_migration?
I understand, that it doesn't directly answers your question, but it's suggesting a possible alternative.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.