Just thought I should post the biggest migrate yet
This one adds a new table for emails and also populates it before removing the email column from User. And it works with both self.up and self.down, although some information is lost on the down-action.
class CreateEmails < ActiveRecord::Migration
def self.up
# create the new table for emails
create_table :emails do |t|
t.column :user_id, :integer
t.column :email, :string
t.column :validation, :string
t.column :created_at, :datetime
t.column :validated_at, :datetime
end
# transfer all old emails to the new table
User.find(:all).each do |user|
user.emails << Email.new(:email => user.email, :validated_at => Time.now())
user.save
end
# remove the old obsolete column
remove_column :users, :email
end
def self.down
# readd the email column
add_column :users, :email, :string
User.reset_column_information
# readd the last validated email to the user
User.find(:all).each do |user|
user.email = user.last_validated_email
user.save
end
# drop the table
drop_table :emails
end
end