If you are using model objects in migrations (e.g. for inserting data) you should make sure that the migration works even if that model class is removed. I discovered this when setting up a new development environment and running all migrations in an empty database.
Let’s say you have the following migration code:
[source:ruby] class InsertCounties < ActiveRecord::Migration def self.up County.create :code => ‘10’, :name => ‘Blekinge’ County.create :code => ‘20’, :name => ‘Dalarna’ end end [/source]
This assumes that the County model is available when the migration is run. If you checked out the most recent version of your code from svn it is possible that it doesn’t contain the County model and the migration will fail. To check if County is available before trying to use it we can use Ruby’s defined? like this:
Update: No we can’t. defined? always returns false inside an ActiveRecord migration for some reason (maybe the class isn’t loaded before the actual call?). We have to use a begin…rescue…end block instead:
[source:ruby] class InsertCounties < ActiveRecord::Migration def self.up begin County.create :code => ‘10’, :name => ‘Blekinge’ County.create :code => ‘20’, :name => ‘Dalarna’ rescue puts “Could not add data…” end end end [/source]
This way the rest of the migrations will run.