Month: May 2007

Validates_uniqueness_of and single table inheritance

Posted by – May 18, 2007

If you’re using STI (single table inheritance) with some Ruby on Rails models, and you need to make sure some fields are unique across all the models, you can use validates_uniqueness_of in the parent model using the :scope option to apply it to all the models. So in this instance since you have a type field in the table, you would use:


validates_uniqueness_of :name, :scope => :type

However, you might encounter trouble with type being a deprecated method that is aliased to class. The fix is to add this before the validation:


undef_method :type

Making Rake tasks ignore Rails observers

Posted by – 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.