Ruby on Rails 2.1.x Migrations

Rails Migration allows you to use 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.
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 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, datetime, 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.

  • integer - is for whole numbers.

  • float - is for decimals.

  • datetime and timestamp - store the date and time into a column.

  • date and time - store 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)
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. Migrations are currently supported in MySQL, PostgreSQL, SQLite, SQL Server, Sybase, and Oracle.

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, its recommended to clean existing migrations generated by model generators. Clean up your subdirectory ~\library\db\migrate before proceeding.
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 lower case 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.
These above two commands will create following files in ~\library\db\migrate subdirectory:
20080613163310_books.rb
20080613163416_subjects.rb
Notice the number prefix for all the files. This is a time stamp used to create a unique file name. This may be different when you will create your migration files.

Edit the code to tell it what to do?

Go into db/migrate subdirectory of your application and edit each file one by one using any simple text editor.
Modify 20080613163310_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 above script will be used to create books table.
Modify 20080613163416_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
Above script will be used to create subjects table and same time it will insert five records in the subjects table.

Run the migration:

Now you have created all the required migration files, its time to execute them against the database. To do this, go to a command prompt and go to the library directory, in which the application is located, and then type rake migratecommand as follows:
C:\ruby\library> rake db:migrate
This will create following three tables in library_development database:

  1. The books table if it doesn't exist.

  2. The subjects table if it doesn't exist.

  3. The schema_migrations 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.
For a detail of these table, login to your database and check all these tables.
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.

No comments:

Post a Comment

Site Search