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,
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
If our model
model_name needed a
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:
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!