Rails Observers, Plugins and Migrations are in a race, who wins?
-
29-10-2019 - |
Question
We just added a couple of observers to our Rails application. Now, when running migrations from scratch we get an error saying that a table doesn't exist (duh, we haven't migrated yet). The error is thrown because a plugin in a model is being loaded that asks for column_names.
I am assuming that the observers are causing the models to be loaded because when we comment out the observers line in application.rb, the error is not thrown.
How do I run migrations without loading observers and models?
or
How do I ask for the column_names in my plugin in a way that won't throw an error when running migrations?
Solution
I haven't found a decent way to disable Observers at run time. This has been previously discussed in Simple way of turning off observers during rake task?
However, I guess you could "unplug" the plugin code from your model by redefining the troublesome model in your migration:
class YourMigration < ActiveRecord::Migraation
class YourModel < ActiveRecord::Base; end
def self.up
...
end
def self.down
...
end
end
OTHER TIPS
In Rails 3 you can skip adding the observers by determining if Rake is being run:
config.active_record.observers = :my_model_observer unless File.basename($0) == 'rake'
This turns off the observers, which means the models and plugins aren't loaded.
In your model you can catch the specific exception generated when you run migrations.