Skip to content

Instantly share code, notes, and snippets.

@mrsweaters
Created April 16, 2018 17:27
Show Gist options
  • Save mrsweaters/a4a3c556a4fcddab4d3dea2102df0357 to your computer and use it in GitHub Desktop.
Save mrsweaters/a4a3c556a4fcddab4d3dea2102df0357 to your computer and use it in GitHub Desktop.
Normalize data in Rails Example
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