An Easy Guide To Using Migrations in Rails

Migrations in Rails are really awesome.

If you haven’t played with them before, migrations allow you to modify the database in atomic steps, making upgrades (and downgrades) much, much, MUCH easier. Every time you run script/generate model [model_name], a corresponding migration is created with a unique number — Rails 2.0.x will add an integer that increases, and Rails 2.1+ adds a timestamp.


001_create_model_name.rb # Old style
20081016230401_create_model_name.rb # New style

Of course, migration scripts aren’t new, but where the Rails ones differ is that they are abstracted so there is no SQL involved (unless you want to use SQL that is). The boiler plate code for a migration looks a little like this:


class CreateModelName < ActiveRecord::Migration
  def self.up
    create_table :model_name do |t|
      
      t.timestamps
    end
  end

  def self.down
    drop_table :model_name
  end
end

The two methods, up and down are pretty self explanatory: up gets called when upgrading the database schema, and down gets called when downgrading, and as you can see up has a create_table method, where down has a corresponding drop_table method.

If our model model_name needed a title, an author_id and active flag, our migration would look something like this:


class CreateModelName < ActiveRecord::Migration
  def self.up
    create_table :model_name do |t|
      t.string :title
      t.integer :author_id
      t.boolean :active
      t.timestamps
    end
  end

  def self.down
    drop_table :model_name
  end
end

The beauty of abstracting things away like this is that you don’t need to worry about nuances between databases. For example, a boolean is represented as a small integer when using MySQL, whilst SQLite has a native boolean type. However if you use Rails migrations, you don’t need to worry about this: Rails takes care of it for you.

What you might not have realised is that the full Rails environment is loaded when migrations are run, so you can actually run code to perform tasks that would be really difficult (or even impossible) with with just straight SQL. For example, maybe you want to create an extra column that holds a version of a document with all the html tags stripped out. In this case you might end up with a migration that looks like this:


class AddStrippedContent < ActiveRecord::Migration
  def self.up
    add_column :stories, :stripped, :text
    
    Stories.find(:all).each do |s|
      s.stripped = s.content.strip_tags
    end
  end

  def self.down
    remove_column :stories, :stripped
  end
end

I find this feature really useful for setting defaults, such as a default admin user or default categories.

Finally, to run a migration, simply type:


rake db:migrate

and to migrate to a specific version, just add a VERSION environment variable:


VERSION=4 rake db:migrate

As you can see, this is much easier than having to remember the equivalent commands in SQL!

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • bert_a

    Simply Rails 2 (and all of the other rails books I have) shows the migration file naming convention is
    001, 002, etc

    When I ran script/generate model User, the migration file was named:
    20081110174511_create_users.rb

    Why does it have this complex number instead of 001? Is there a way to
    redo this and get the simpler name?

  • madpilot

    bert_a: You must be running Rails 2.1 or higher, as this is the new way the migration numbering works. That large number is a timestamp, which stops the problem that occurs when two developers create a new table separately and end up with clashing migration numbers.

    I’m not aware of a plugin that reverts it (That doesn’t mean it doesn’t exist though!)

  • bert_a

    Thank you very much! I thought I did something wrong.