Rails Simplified: Migrations
Posted By Slobodan Kovacevic on December 25, 2006
When you start learning Ruby and Ruby on Rails you are faced with very powerful set of tools and sometimes it can be overwhelming. You are often faced with long cryptic explanation of some feature and all you want is a quick overview of what it does and how you could use it.
Rails Simplified will be a series of posts is giving you a brief description of various Ruby / Rails related features, as well as pointer to other articles that give you a more in-depth view of those features. Rails Simplified - Migrations will be the first one in this series…
Rails Migrations
What are migrations?
Migrations are an easy way to manage your database schema in a way that you can easily synchronize it between different servers (for example between development and production server). Simply put: you can write code that can upgrade or downgrade your database schema - think of it as database versioning.
If you did any programming you probably know how hard it can be to keep track of database changes - migrations make your life a lot easier.
How do you use migrations?
- Create migration using: ./script/generate migration ShortDescriptionChange
- Edit file that was created in db/migrate dir and describe changes that need to be made
- Run rake migrate which brings your database up to date
How do you describe schema changes?
Once you create migration defined class will have two methods self.up (used when upgrading schema) and self.down (downgrade schema). If you want to create a table you’d write code like this:
def self.up
create_table :lists do |t|
t.column :name, :string
t.column :description, :string
t.column :created_on, :datetime
end
end
def self.down
drop_table :lists
end
First method defines table that needs to be created (notice that it’s database independent) and second provides a way to undo changes made by this migration.
These are just a simple example and you can do a lot more using migrations - change existing tables, delete tables, insert default values to tables and if necessary you can even execute plain SQL code.
Where can I get more information about Rails migrations?
- Rails API Class ActiveRecord::Migration - it describes everything you can do with Rails migrations.
- Screencast about Rails Migrations
- The Joy of Migrations - more detailed post on migrations.
- Rails Migration Cheat Sheet
- Foreign key and rails migration - an excellent helper method that fixes an oversight in Rails migrations (you cannot define foreign keys natively).