Ruby on Rails
UnderstandingMigrations

What are migrations?

ActiveRecordMigration allows you to use Ruby to define changes to your database schema, making it possible to use a version control system to keep things synchronized with the actual code.

This has many uses, including:

How do I use them?

Create the migration

Run the generator:


ruby script/generate migration add_a_new_table

(Note that migrations should be under_scored or CamelCased, just like models, controllers and views.)

This will create the file db/migrate/001_add_a_new_table.rb

Edit the code to tell it what to do.

The method self.up is used when migrating to a new version, self.down is used to roll back any changes if needed. The class name needs to be the same as the migration name (i.e. db/migrate/001_add_a_new_table needs a class name of AddANewTable).

The ID column will be created automatically, so don’t do it here as well.


  class AddANewTable < ActiveRecord::Migration
    def self.up
      create_table :users do |table|
        table.column :name, :string
        # This column will contain an MD5 hash.
        table.column :login,  :string, :null => false
        table.column :password, :string, :limit => 32, :null => false
        table.column :email, :string       
      end
    end

    def self.down
      drop_table :users
    end
  end

Valid column types are decimal, integer, float, datetime, date, timestamp, time, text, string, binary, and boolean.

Valid column options are:

You can also populate or modify data in a migration. A common usage would be to populate the values in a lookup table:


def self.up
  create_table :statuses do |t|
    t.string :name
  end

  Status.create :name => "Complete" 
  Status.create :name => "Incomplete" 

end

Run the migration


rake db:migrate

This will create a “schema_info” table if it doesn’t exist which tracks the current version of the database – each new migration will be a new version, and any new migrations will be run until your database is at the current version.

Running migrations for production and test databases

If you would like to specify what rails environment to use for the migration, use the RAILS_ENV shell variable.

For example:


$ export RAILS_ENV=production
$ rake db:migrate

$ export RAILS_ENV=test
$ rake db:migrate

$ export RAILS_ENV=development
$ rake db:migrate

Note: On Windows, use “set RAILS_ENV=production” instead of export

How do I populate a database with associations?


See UsingMigrations for more in-depth information.

category: Understanding


For beginners and experts, there’s a compact Rails Migrations cheatsheet in printable PDF format, which makes a brilliant at-a-glance reference: Rails Migrations Cheatsheet