Skip to content

Instantly share code, notes, and snippets.

@stevenyap
Created October 19, 2013 07:47
Show Gist options
  • Save stevenyap/7052784 to your computer and use it in GitHub Desktop.
Save stevenyap/7052784 to your computer and use it in GitHub Desktop.
Migrating database/schema changes to app and heroku

Setup

You want to add a new column, remove a column, add a reference, etc to your existing schema. This gist will show you the steps.

Create a migration

rails g migration AddStockToProducts
  • Use meaningful names and CamelCases
  • The above will create a migration file: /db/migrate/20131019071517_add_stock_to_products.rb

Add your changes to the migration file

# Common usages
add_column :products, :stock, :integer, default: 0
remove_column :products, :short_description, :text

add_reference :categories, :products, index: true
remove_reference :categories, :products, index: true

change_column :products, :email, :string
rename_column :products, :email, :customer_email

# Custom up and down migration
def up
  # custom code to convert your data esp data column migration
end

def down
  # custom code to revert back for consistency
end

# table with no primary key
create_table :appointments, id: false do |t|
  t.integer :doctor_id
  t.integer :patent_id
  
  # or
  
  t.references :doctor, index: true
  t.references :patent, index: true
end

Run rake migration

rake db:migrate db:test:prepare

Push to Heroku

  • Remember to rspec and push to git first
git push heroku master

IMPORTANT: Need to migrate DB on Heroku and RESTART app

heroku run rake db:migrate
heroku restart
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment