Panasonic Youth rob sanheim writes about software, business, ruby, music, stuff and things



Posted
8 January 2008 @ 11am

Tagged
Rails

Discuss

Rails observers make rake db:migrate crash from version 0

Rails observers are typically defined like this in environment.rb:

RUBY:
  1. Rails::Initializer.run do |config|
  2.   config.action_controller.session_store = :active_record_store
  3.   config.active_record.observers = :user_observer
  4. end

I recently hit an issue where a fresh db:migrate of an app with a standard observer blew out every time. After some digging into the trace, I saw it was due to rake loading environment.rb, which fires up the observer, which then loads the observed model -- which of course does not exist yet since the database is at version 0. I'm guessing you won't always see this error, as the DB call is triggered by certain validations -- if your model is relatively free of validations I imagine you may be fine.

Some googling led me to James Robey's proposed fix, which as the downfall of disabling the observer for any call to rake. This little hack should be a bit better, in that it will only disable the observer for rake db:migrate calls:

RUBY:
  1. # observers break a migrate from VERSION 0 - disable them for rake db:migrate
  2. unless ( File.basename($0) == "rake" && ARGV.include?("db:migrate") ) 
  3.   config.active_record.observers = :user_observer
  4. end

Go forth, and migrate from version 0 with impunity.


2 Comments

Posted by
Jon Larkowski
8 January 2008 @ 1pm

Thanks! This issue rears its ugly head from time to time. Glad to have a fix finally! I added some more tasks I needed covered.

unless ((File.basename($0) == “rake”) && (%w{create drop migrate reset}.any? { |task| ARGV.include?(”db:#{task}”) }))


Posted by
Flinn
14 April 2008 @ 11am

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

How I Spent My Christmas Vacation untitled