Using the latest attributes in a Rails migration

Occasionally I need to make some change to a table via migrations, and then immediately use the attributes associated with the latest table inside the migration. Most of the time you can do this by defining the aspects of the class inside the migration – for example:

class AddDepartmentToProducts < ActiveRecord::Migration

  class Product < ActiveRecord::Base
    belongs_to :department
  end

  def self.up
    add_column :products, :department_id, :integer
    # do something with product.department
  end

  def self.down
    #...
  end

end

There’s also another way that’s not as neat, but gives you finer grained control, for example if you need to have different definitions of the class in the up and down migrations:

class AddDepartmentToProducts < ActiveRecord::Migration

  def self.up
    add_column :products, :department_id, :integer
    Object.class_eval <<-end_eval
    class Apparel21::Product < ActiveRecord::Base
      belongs_to :department
    end
  end_eval
    # do something with product.department
  end

  def self.down
    #...
  end

end

~ by Steve Hayes on February 11, 2008.

Leave a Reply