1.9. ActiveRecord and Models

ActiveRecord connects business objects and database tables to create a persistable domain model where logic and data is presented in one wrapping. For more on ActiveRecord, go to http://ar.rubyonrails.com.

1.9.1. Migrations

Think of migrations as a version repository for the database schema. With migrations, you are able to create versions of your database schema and go forward or backward to whichever version you want. This makes it very convenient for developers who want to just add small changes to a table without having to rebuild the whole database.

Rails provides a generator for creating migrations:

./script generate migration MigrationName [options]

In the previous example, the generator creates a migration class in db/migrate with its version number prefixed to the name. In Rails 2.1, UTC-based migrations were introduced, which use a unique prefix that is less likely to conflict with another migration that somebody else happens to check in around the same time.

Example:

class CreateMovies < ActiveRecord::Migration
  def self.up
    create_table :movies do |t|
      t.string  :title
      t.integer :genre_id
      t.string  :rating, :limit => 5
      t.string  :short_description
      t.text    :long_description
      t.boolean :is_new_release, :default => false
      t.timestamps
    end

    # Add foreign key
    add_index :movies, :genre_id
  end

  def self.down
    drop_table :movies
  end
end

In this example, we are creating a table named movies with the columns title, genre_id, rating, short_description, long_description ...

Get Rails Pocket Reference now with O’Reilly online learning.

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