Ruby on Rails Migrations

Migrations are a way to alter database schema over time in a consistent and organized manner. They use a Ruby DSL through which there is no need to write SQL by hand.

SQL fragments can be edited by hand but then you have to tell other developers about the changes you made and then run them. You need to keep track of changes that need to be run against production machines next time you deploy.

Each migration is a new version of the database. Each migration modifies database by adding or removing tables, columnns or entries. Active record will update your db/schema.rb file to match up-to-date structure of your database.


Purpose of Migrations

It is important to know the purpose of migration before using it. Database is used in all web applications.

Generally, a SQL statement is used to run database queries to create, modify, read or delete columns of a database.

Migration file contains a specific set of instructions for how a database should be created. When this file is run, Rails will make changes in the database automatically. Gradually, the migration file will act as a versioned history of how database has changed. It implies that you will be able to recreate the database from the set of instructions file.


Creating Migration file

Syntax to create a migration file:

application_dir> rails generate migration table_name  

This will create a file with the name db/migrate/001_table_name.rb. A migration file contains basic data structure of a database table.

It is advisable that before running the migration generator, clean the existing migrations generated by model generators.

Example:

ADVERTISEMENT

ADVERTISEMENT

Let us create a migration called java in the application tutorials.

rails generate migration java  
Ruby On rails migrations 1

Editing Code

Go to db/migrate directory in the tutorials application. Write the followig code in the present file 001_java.rb,

class Java < ActiveRecord::Migration   

     

   def self.up   

      create_table :java do |t|   

         t.column :title, :string, :limit => 32, :null => false   

         t.column :fee, :float   

         t.column :duration, :integer   

         t.column :index, :string   

         t.column :created_at, :timestamp   

      end   

   end   

  

   def self.down   

      drop_table :java   

   end   

end

The method self.up is used during migrating to a new version and self.down is used to roll back any changes if needed.


Run Migration

After creating all the required migration files you need to execute them. To execute migration file against database, run the following code:

rake db:migrate  

It will create a “schema_info” table if doesn’t exist. It tracks the current version of the database.

If new migration will be created then that will be a new version for the database.

Ruby On rails migrations 2

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *