Main Contents

Making Rake tasks ignore Rails observers

May 16, 2007

Have you ever run “rake db:migrate” on an empty database (or you did “rake db:migrate VERSION=0″ to empty the database). And then it fails on you like this?


rake db:migrate
(in /Users/foucist/rails/myproject)
rake aborted!
Mysql::Error: #42S02Table 'myproject_development.users' doesn't exist: SHOW FIELDS FROM users
(See full trace by running task with --trace)

Invariably, rake failures are caused by something in the environment file that is expecting something in the database. Sometimes people stick a .find() in the environment file unfortunately. In this case, it turned out to be the user observer.


Rails::Initializer.run do |config|
config.action_controller.session_store = :active_record_store
config.active_record.observers = :user_observer
end

After examining the code for the rake tasks in /opt/local/lib/ruby/gems/1.8/gems/rails-1.2.3/lib/tasks/ I noticed that the environment file was loaded with ‘require’. That means that environment.rb is code (obviously) and now I can change the line for the user observer to not load when rake is loading it.


config.active_record.observers = :user_observer unless File.basename( $0 ) == "rake"

Viola. File.basename is just a trick to parse the $0 variable which is the name of the binary thats loading the file.

Filed under: Ruby on Rails |

1 Comment

  1. Flinn April 14, 2008 @ 10:36 am

    You can also not use config/environments.rb to load observers and instead use config/initializers/observers.rb like so:


    ActiveRecord::Base.observers = :cacher, :garbage_collector
    ActiveRecord::Base.instantiate_observers

Leave a comment