h3. What are migrations? ActiveRecordMigration allow you to use Ruby to define changes to your database schema, making it possible to use a version control system to keep things synchronised with the actual code. This has many uses, including: * Teams of developers - if one person makes a schema change, the other developers just need to update, and run "@rake migrate@". * Production servers - run "@rake migrate@" when you roll out a new release to bring the database up to date as well. * Multiple machines - if you develop on both a desktop and a laptop, or in more than one location, migrations can help you keep them all synchronised. h3. How do I use them? h4. Create the migration Run the generator:
script/generate migration add_a_new_table
This will create the file @db/migrations/1_add_a_new_table.rb@
h4. 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 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
table.column :login, :string
# This column will contain an MD5 hash.
table.column :password, :string, :limit => 32
table.column :email, :string
end
end
def self.down
drop_table :users
end
end
h4. Run the migration
rake 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.
h4. So all the figuring out when to run each migration is all Rails magic, then?
h4. Can this be used in place of an initial DB schema, if you'd rather describe everything about your model with Ruby code to begin with?
Yes it can. I'm using this very method, as it's much easier to do this than create a bunch of different SQL files for each database.
-- MattMoriarity
*Question*: How does the rake provide ordering to the migrations? Imagine 2 migrations...
* A - creates a table FOO
* B - adds a new column to table FOO
How does rake ensure that A runs before B?
The files are prefixed with a number. So the first migration you make will be called @1_add_flag.rb@, the next will be @2_add_table.rb@. Use the "@script/generate migration@" command and it'll do this automatically.
*Question:* How do you tell rake to un-migrate back to a specific version?
You can migrate to privious versions by passing in a value for @VERSION@
*Ex: migrate back to initial version*
rake migrate VERSION=0
*Question:* How do you tell rake to operate on your production database?
rake environment RAILS_ENV=production migrate
category: Understanding