Skip to content

Instantly share code, notes, and snippets.

@darwingr
Last active September 12, 2015 07:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darwingr/fc65c17eaaee145dad3e to your computer and use it in GitHub Desktop.
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.
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
@darwingr
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment