Created
April 16, 2018 17:27
-
-
Save mrsweaters/a4a3c556a4fcddab4d3dea2102df0357 to your computer and use it in GitHub Desktop.
Normalize data in Rails Example
This file contains hidden or 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 CreateAddresses < ActiveRecord::Migration | |
def self.up | |
create_table :addresses do |t| | |
t.integer :customer_id | |
t.string :address | |
t.string :city | |
t.string :state | |
t.integer :zip_code | |
t.timestamps | |
end | |
# move customer address fields to address table | |
Customer.all.each do |c| | |
Address.create({ | |
:customer_id => c.id, | |
:address => c.address, | |
:city => c.city, | |
:state => c.state, | |
:zip => c.zip | |
}) | |
end | |
# you'll have to write your own merge script here | |
# use execute("your sql goes here...") if you can't do it with ActiveRecord methods | |
# remove old customer address columns | |
remove_columns(:customers, :address, :city, :state, :zip) | |
end | |
def self.down | |
# here you will define the reverse of the self.up method | |
# re-add the address columns to the user table | |
# repopulate the customer table with data from the address table | |
drop_table :addresses | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment