Manipulating Data

Sometimes you want to change the database and massage the data so that it will fit with the new schema. For this to work, the migration should do two things:

  1. turn off timestamps by setting record_timestamps to false so that when you save records they will not show up as recently modified.
  2. call reset_column_information so that the new columns that have been added in the same migration will show up in the ActiveRecord objects.
class SplitProfileNameIntoFirstAndLastNames < ActiveRecord::Migration

  def self.up
    add_column :profiles, :first_name, :string
    add_column :profiles, :last_name, :string

    ActiveRecord::Base.record_timestamps = false
    Profile.reset_column_information    
    Profile.find(:all).each do |profile|
      profile.first_name = profile.name.split(" ").first
      profile.last_name  = profile.name.split(" ").last
      profile.save!
    end

    remove_column :profiles, :name
  end

  def self.down
    add_column :profiles, :name, :string

    ActiveRecord::Base.record_timestamps = false
    Profile.reset_column_information
    Profile.find(:all).each do |profile|
      profile.name = profile.first_name + " " + profile.last_name
      profile.save!
    end

    remove_column :profiles, :first_name
    remove_column :profiles, :last_name
  end
end