Skip to content

Instantly share code, notes, and snippets.

@tochman
Last active November 25, 2017 08:14
Show Gist options
  • Save tochman/c249b48a7b203ee06c9f14c4392086a6 to your computer and use it in GitHub Desktop.
Save tochman/c249b48a7b203ee06c9f14c4392086a6 to your computer and use it in GitHub Desktop.
Active Record Migration Cheat Sheet

Active Record Migrations

Migrations are a feature of Active Record that allows you to evolve your database schema over time. Rather than write schema modifications in pure SQL, migrations allow you to use an easy Ruby DSL to describe changes to your tables.

Migrations methods

  • up
    • change_table
    • create_table
    • add_column
    • add_index
    • change_column
    • drop_table
    • remove_column
    • remove_index
    • `rename_column

Create a table

class CreateUsers < ActiveRecord::Migration[5.0]
  def up
    create_table :users do |t|
      t.string :name
      t.string :email
    end
  end
end

Available column types:

:string 
:text 
:integer 
:float 
:decimal  
:datetime
:timestamp
:time
:date
:binary
:boolean

## Change a table
```ruby
class ChangeUsers < 
  def change
    #your commands
  end
end

Exmples

Add a column

# Add one column
class AddDescriptionToProduct < ActiveRecord::Migration[4.2]
  def change
    add_column :products, :description, :text
  end
end
# Add multiple columns to a table
class AddDescriptionToProduct < ActiveRecord::Migration[4.2]
  def change
    add_column :products, :description, :text
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment