You are here: Home Solidarrow Ruby on Rails Solidarrow Migrations

* Rails Migrations Cheatsheet

Up and down methods, rake tasks, database mapping, loading fixtures, example migration file, all packed onto one A4 page for an easy at-a-glance reference

Methods

add_column

Creates a new column on the specified table.

    add_column :table_name, :column_name, :column_type, { options }

  • :null => true or false - if false, the underlying column has a NOT NULL constraint added by the database engine
  • :limit => size - set a limit on the size of the field
  • :default => value - set a default value for the column

add_index

Creates an index for the specified table, the name of which defaults to table_column_index

    add_index :table_name, :column_name, :unique => true, :name => "chosen_index_name"

change_column

Change the data type of the specified column

    change_column :table_name, :column_name, :new_type, { options as add_column }

create_table

Creates a table on the database. Creates a table called :table_name and makes the table object available to a block that can then add columns to it, following the same format as add_column.

    create_table :table_name, { options } do |t|
      t.column :column_name, :column_type, :options
    end

  • :force => true - forces drop of an existing table of the same name before creation the new one
  • :temporary => true - creates a temporary table, one that goes away when the application disconnects from the database
  • :id => false - defines a table with no primary key, for example when you need to define a join table
  • :primary_key => :new_primary_key_name - overrides the default name of id for the primary column, use this to specify the name of the column in the database that Rails will use to store the primary key
  • :options => "" - lets you specify options to your underlying database, e.g. "auto_increment = 10000". Will lose default "ENGINE=InnoDB statement".

execute

Takes a single string identifying a valid SQL command to execute directly

    execute "alter table line_items add constraint fk_line_item_products foreign key (product_id) references products(id)"

IrreversibleMigration

Use in the down method of a migration file to raise an exception when the up methods of the same migration file can not be reversed, e.g. changing a column type from :integer to :string

    raise ActiveRecord::IrreversibleMigration

rename_table

Renames the specified table.

    rename_table :new_table_name, :old_table_name

rename_column

Renames the old_column_name to new_column_name

    rename_column :old_column_name, :new_column_name

rename_table

Renames the specified table.

    rename_table :new_table_name, :old_table_name

remove_index

Remove an index for the specified table.

    remove_index :table_name, :column_name



Database Mapping

Rails

db2

mysql

openbase

Oracle

:binary

blob(32678)

blob

object

blob

:boolean

decimal(1)

tinyint(1)

boolean

number(10)

:date

date

date

date

date

:datetime

timestamp

datetime

datetime

date

:decimal

decimal

decimal

decimal

decimal

:float

float

float

float

number

:integer

int

int(11)

integer

number(38)

:string

varchar(255)

varchar(255)

char(4096)

varchar2(255)

Rails

postgresql

sqlite

sqlserver

Sybase

:binary

bytea

blob

image

image

:boolean

boolean

boolean

bit

bit

:date

date

date

datetime

datetime

:datetime

timestamp

datetime

datetime

datetime

:decimal

decimal

decimal

decimal

decimal

:float

float

float

float(8)

float(8)

:integer

integer

integer

int

int

:string

*

varchar(255)

varchar(255)

varchar(255)

Example migration file

    class CreateCustomers < ActiveRecord::Migration

    def self.up
        # Create "Customers" table
        create_table :customers, :primary_key => :customer_id, :options => "auto_increment = 10000" do |t|
          # Add columns to "Customers" table
          t.column :customer_id, :integer
          t.column :name,        :string,    :limit => 30, :null => false
          t.column :age,         :integer
          t.column :premium,     :boolean,   :default => 0
          t.column :photo,       :binary,    :limit => 2.megabytes
          t.column :thumbnail,   :binary,    :limit => 256.kilobytes
          t.column :dob,         :date,      :null => false
          t.column :created_at,  :timestamp
          t.column :notes,       :text,      :default => "No notes recorded"
      end
      # Add "surname" column to "Customers" table 
      add_column :customers, :surname,   :string,   :limit => 50
      # Add "price" column to "Orders" table
      add_column :orders,    :price,     :decimal,  :precision => 8, :scale => 2
      # Create a record on the "Customers" table
      Customer.create :name => "David", :surname => "Smith", :age => "32", :premium => "1", :notes => "One of our top customers!"
    end

    def self.down 
      # Delete the "Customers" table
        drop_table :customers
      end
    end



Rake tasks

Generate migration

ruby script/generate migration your_chosen_migration_name

run all unapplied migrations

rake db:migrate

migrate database to specific version

rake db:migrate VERSION=18

use your migrations to recreate the tables in the testing or production databases

rake db:migrate RAILS_ENV=production

Create a db/schema.rb file that can be portably used against any database supported by ActiveRecord

rake db:schema:dump

Load a schema.rb file into the database

rake db:schema:load

Loads a schema.rb file into the database and then loads the initial database fixtures.

rake db:bootstrap

Directory structure

  • rails_root
    • db
      • schema.rb
      • migrate
        • 001_create_customers
        • 002_add_photo
        • 003_alter_surname

Testing a new section.

 

* Comments

4 MONTHS AGO

Very Beneficial

Very Beneficial resource code.

4 MONTHS AGO

migrate

beneficial

3 MONTHS AGO

Very nice - one small bug

Thank you for the organized approach to looking at migrations - much appreciated. One small item - I noticed in the PDF version, the rename_column item uses rename_table in the code example (rename_table :old_column_name, :new_column_name).

ABOUT 1 MONTH AGO

Very nice, buy one type is missing

Very nice, buy one type is missing. It's :text. Representing TEXT in mysql.

ABOUT 1 MONTH AGO

Drops?

What about drops for migrating down

27 DAYS AGO

Cortesy

what ahout a little bit of courtesy? So, when you find an excelent guide to migrations, the only thing to say is "What about drops for migrating down" pff...

27 DAYS AGO

Drops?

"So, when you find an excelent guide to migrations, the only thing to say is "What about drops for migrating down" pff..." Exactly what i mean.. it would be an "excellent" guide if it had drop syntax, that's not discourteous at all.

7 DAYS AGO

rename_table args reversed

Thanks for this very useful resource. The args for rename_table should be :old_table, :new_table (and rename_table is actually listed twice too).

3 MINUTES AGO

rename_column is wrong too

You're missing the table argument from the rename_column syntax as well.

 

> RELATED ARTICLE

* New in Rails 2.0: Sexy Migrations

A look at the new features and syntax available in migrations on Rails 2.0 > More

 

> RELATED ARTICLE

* Auto migrations

A brilliant plugin that makes changing your database schema even easier and faster. > More