rod mclaughlin


Issues with migrations in Ruby on Rails (09 feb 13)

The biggest problem I have encountered with migrations is this: 

You add a field to a model. You add validation for that field. You write a migration that adds that column to the table corresponding to that model. It works in development and test. You send it to a customer who has code which is several versions old. They try to run several migrations. They break, because they load the new app with the new model, which refers to columns which don't exist in their old database.

 

==  RenameLoginToEmail: migrating =============================================
-- rename_column(:users, :login, :email)
rake aborted!
An error has occurred, all later migrations canceled:
No such column: users.login

 

Here's a workaround - db/migrate/20130211000000_rename_login_to_email.rb:

class RenameLoginToEmail < ActiveRecord::Migration
  def self.up
    begin
      rename_column :users, :login, :email
    rescue Exception => x
      raise x unless x.message =~ /No.+column.+login/i
    end
  end
  def self.down
    begin
      rename_column :users, :email, :login
    rescue Exception => x
      raise x unless x.message =~ /No.+column.+email/i
    end
  end
end

What's really needed is a way of tying migrations to source control. Checkout code version N. Run migration N. Checkout code version N+1. Run migration N+1 etc..

More:

http://simononsoftware.com/why-ruby-on-rails-migrations-dont-work




Back
Portland London