Inside Migrations

The easiest way to familiarize yourself with migrations is (as is often the case with Rails) to examine what Rails puts in them with script/generate. In Chapter 9 we created a students model with:

script/generate scaffold student given_name:string middle_name:string
family_name:string date_of_birth:date grade_point_average:decimal start_date:date

That code generated many files, but the migration it created went into db/20080701211008_create_students.rb and contained the code shown in Example 10-3.

Example 10-3. Code for setting up a table, generated by a scaffolding call

class CreateStudents < ActiveRecord::Migration
  def self.up
    create_table :students do |t|
      t.string :given_name
      t.string :middle_name
      t.string :family_name
      t.date :date_of_birth
      t.decimal :grade_point_average
      t.date :start_date

      t.timestamps
    end
  end

  def self.down
    drop_table :students
  end
end

You can also generate migrations with script/generate migration migration_name or, in Heroku, by going to the gear menu, choosing Generate, and entering migration migration_name. Normally, migrations that create new tables start their names with create, while migrations that add to existing tables start their names with add.

Working with Tables

Most of the activity in the migration generated by the scaffolding, shown in Example 10-1, is in the self.up method. self.down drops the whole students table, which also disposes of any contents it had, so it can skimp on details, just ordering drop_table :students. As you might ...

Get Learning Rails now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.