Copyright © tutorialspoint.com

# Rails 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)

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, its recommended to clean 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 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.

## 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 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.column :title, :string, :limit => 32, :null => false
    	t.column :price, :float
    	t.column :subject_id, :integer
    	t.column :description, :text
    	t.column :created_at, :timestamp
         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 002_subjects.rb as follows:

    class Subjects < ActiveRecord::Migration
      def self.up
          create_table :subjects do |t|
           t.column :name, :string
        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 will create 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 migrate command 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 required Tables available. In the two subsequent chapters we will explore two important components called Controller (ActionController) and View (ActionView).

1. Creating Controllers ( Action Controller )
2. Creating Views ( Action View )

Copyright © tutorialspoint.com