Data massaging in migrations and errors after refactoring 4

Posted by Tim Connor Thu, 22 Mar 2007 16:43:00 GMT

ActiveRecord migrations are a powerful tool for handling your database schema changes. Not only that, but you can run any AR code in them to tweak that data itself while migrating to the new structure, such as.

class AddUpdatedAtToReport < ActiveRecord::Migration
  def self.up
    add_column :fishing_reports, :updated_at, :datetime
    FishingReport.find(:all).each do |r|
      r.updated_at = Time.now
      r.save
    end
  end
  def self.down
    remove_column :fishing_reports, :updated_at
  end
end

Unfortunately this can lead to the migration becoming not only obselete but outright incompatible later, throwing errors. For instance, if you later refactor that model out of existence, the migration will fail, because there is no model to match FishingReport. I suspect there could be some future proofing done, by checking for the existence of the class, but one can easily imagine refactorings that wouldn’t be so easily guarded against.

I suppose that could be an excuse for more testing: migration testing. In fact, after using typo for a while, i think migration testing should maybe be a recommended paractice for any publically distributed Rails app.