Reputation: 19938
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...
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
Upvotes: 2
Views: 1327
Reputation: 15045
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::Base.connection.migration_context.needs_migration?
I understand, that it doesn't directly answers your question, but it's suggesting a possible alternative.
Upvotes: 3