Last active
September 12, 2015 07:50
-
-
Save darwingr/fc65c17eaaee145dad3e to your computer and use it in GitHub Desktop.
Moving columns to a new empty table, the foreign keys are already in place.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MoveAttributesToRegistrantModel < ActiveRecord::Migration | |
def up | |
Payment.find_each do |payment| | |
registrant = Registrant.create! email: payment.email, | |
first_name: payment.first_name, | |
last_name: payment.last_name | |
payment.registrant_id = registrant.id | |
payment.save! | |
end | |
remove_column :payments, :email | |
remove_column :payments, :first_name | |
remove_column :payments, :last_name | |
end | |
def down | |
add_column :payments, :email, :string | |
add_column :payments, :first_name, :string | |
add_column :payments, :last_name, :string | |
Registrant.find_each do |registrant| | |
payment = Payment.find_by! registrant_id: registrant.id | |
payment.update! email: registrant.email, | |
first_name: registrant.first_name, | |
last_name: registrant.last_name | |
registrant.delete | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
EDITS MIGRATION file that was not yet in production.
Removes selecting where email was not missing, which irreversibly deleted records outside this case.
Also uses bang methods so any failed validations will cause the migration to abort.