Ruby on Rails 2.1 - Migrations



Rails Migration uses Ruby to define changes to your database schema, making it possible to use a version control system to keep things synchronized with the actual code.

It has many uses, such as −

  • 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 synchronized.

What can Rails Migration Do?

  • create_table(name, options)

  • drop_table(name)

  • rename_table(old_name, new_name)

  • add_column(table_name, column_name, type, options)

  • rename_column(table_name, column_name, new_column_name)

  • change_column(table_name, column_name, type, options)

  • remove_column(table_name, column_name)

  • add_index(table_name, column_name, index_type)

  • remove_index(table_name, column_name)

Migrations support all the basic data types − string, text, integer, float, date-time, timestamp, time, date, binary and Boolean −

  • string − is for small data types such as a title.

  • text − is for longer pieces of textual data, such as the description.

  • text − is for longer pieces of textual data, such as the description.

  • integer − is for whole numbers.

  • float − is for decimals.

  • date-time and timestamp − stores the date and time into a column.

  • date and time − stores either the date only or time only.

  • binary − is for storing data such as images, audio, or movies.

  • boolean − is for storing true or false values.

Valid column options are −

  • limit ( :limit => “50” )

  • default (:default => “blah” )

  • null (:null => false implies NOT NULL)

NOTE − The activities done by Rails Migration can be done using any front-end GUI or direct on SQL prompt, but Rails Migration makes all those activities very easy

See the Rails API for details on these.

Create the Migrations

Here is the generic syntax for creating a migration −

C:\ruby\application> ruby script/generate migration table_name

This will create the file db/migrate/001_table_name.rb. A migration file contains basic Ruby syntax that describes the data structure of a database table.

NOTE − Before running migration generator, it is recommended to clean the existing migrations generated by model generators.

We will create two migrations corresponding to our three tables - books and subjects..

C:\ruby> cd library
C:\ruby\library> ruby script/generate migration books
C:\ruby\library> ruby script/generate migration subjects

Notice that you are using lowercase for book and subject and using the plural form while creating migrations. This is a Rails paradigm that you should follow each time you create a Migration. −

Edit the Code to Tell it What to Do

Go to db/migrate subdirectory of your application and edit each file one by one using any simple text editor.

Modify 001_books.rb as follows −

The ID column will be created automatically, so don't do it here as well.

class Books < ActiveRecord::Migration
   def self.up
      create_table :books do |t|
         t.string     :title, :limit => 32, :null => false
         t.float      :price
         t.integer    :subject_id
         t.text       :description
         t.timestamp  :created_at
      end
   end
   def self.down
      drop_table :books
   end
end

The method self.up is used when migrating to a new version, self.down is used to roll back any changes if needed. At this moment, the above script will be used to create the books table.

Modify 002_subjects.rb as follows −

class Subjects < ActiveRecord::Migration
   def self.up
      create_table :subjects do |t|
         t.string :name
      end
      Subject.create :name => "Physics"
      Subject.create :name =>"Mathematics"
      Subject.create :name => "Chemistry"
      Subject.create :name => "Psychology"
      Subject.create :name => "Geography"
   end
   def self.down
      drop_table :subjects
   end
end

The above script will be used to create subjects table; it will create five records in the subjects table.

Run the Migration

Now that you have created all the required migration files, it is time to execute them against the database. To do this, go to the command prompt and open the library directory in which the application is located, and then type rake migrate as follows −

C:\ruby\library> rake db: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.

Rake is a Ruby build program similar to Unix make program that Rails takes advantage of, to simplify the execution of complex tasks such as updating a database's structure etc.

Running Migrations for Production and Test Databases

If you would like to specify what rails environment to use for the migration, use the RAILS_ENV shell variable.

For example −

C:\ruby\library> set RAILS_ENV=production
C:\ruby\library> rake db:migrate
C:\ruby\library> set RAILS_ENV=test
C:\ruby\library> rake db:migrate
C:\ruby\library> set RAILS_ENV=development
C:\ruby\library> rake db:migrate

NOTE − On Unix, use "export RAILS_ENV=production" instead of set command.

What is Next?

Now we have our database and the required tables available. In the two subsequent chapters, we will explore two important components called Controller (ActionController) and View (ActionView).

  • Creating Controllers ( Action Controller )
  • Creating Views ( Action View )
Advertisements