Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Migrations and its Features
2.1.
Uses
2.2.
Functions
3.
Operations in Migrations
3.1.
Create the migrations
3.2.
Edit the Code
3.3.
Run the Migration
3.4.
Running Migrations for Production and Test Databases
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024

Ruby on Rails- Migrations

Author Naman Kukreja
0 upvote

Introduction

In today’s world, all websites have their databases, and they have to alter them continuously in a structured and organized manner. Users can achieve this with the help of SQL, but there are some constraints, like they have to tell other developers about the change and perform the changes by themselves. So is there any better way to perform these actions?

The answer is yes. We can perform all these operations efficiently and quickly with the help of migrations. As in migrations, we have the active record we keep the record of all the migrations that have been run, so we need to update the source code.

Migrations and its Features

Migrations in Rails allow users to use Ruby to define changes in the database's schema, keeping a synchronized actual code with the help of version controls.

Uses

  • Production servers - To update the database, just run the “rake migrate” command whenever you roll out a new release.
  • Multiple machines - This helps to keep all the code synchronized when you develop on more than one machine-like on a laptop and desktop.
  • Teams of developers -  As discussed earlier, other team members have to run the "rake migrate" command no matter how big the team is and who changes the schema.

Functions

  • rename_table(old_name,new_name)
  • rename_coloumn(table_name, new_column_name, column_name,)
  • change_column(table_name, type, column_name, options)
  • remove_index(table_name, column_name)
  • add_index(table_name, index_type, column_name)
  • drop_table(name)
  • create_table(name, options)
  • remove_coloumn(table_name, column_name)

 

Migration supports the following data types:

  • string − for small data types such as a title.
  • text − for textual data, such as the description.
  • date and time − store either the date only or time only.
  • integer − for whole numbers.
  • binary − for storing data such as images, movies, or audio.
  • float − for decimals.
  • datetime and timestamp − store the date and time into a column.
  • Boolean − for storing true or false values.

 

There are some valid column options the list is given below:

  • null(: null=> false implies NOT NULL)
  • limit(: limit=>”22”)
  • default(: default=>” Something”)

Operations in Migrations

Now, we will see how to create migrations, edit them, and run them.

Create the migrations

Here is the syntax for creating migration:

application_dir> rails generate migration table_name.

After running the above command, the file db/migrate/001_table_name.rb is created. This file contains the basic Ruby Syntax explains the data structure of the database table.

Corresponding to our three tables, we will create two migrations.

Books migrations are as follows:

tp> cd library
library> rails generate migration books

The above command generates the following code:

Subject migration should be as follows:

tp> cd library
library> rails generate migration subjects

The above command generates the following code:

 Make sure that you use plural form while creating migration and lower case for the subject. This is the syntax that you have to follow whenever working with rails.

Edit the Code

Users can use any text editor of their choice in their application. You have to go to db/migrate subdirectory to edit.

Modify 001_books.rb like the following code:

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

When migrating to a new version, method self.up is used. If you want to roll back any changes, you can use self.down. Now the above script is used to create a book table.

Now change 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.Download
      drop_table :subjects
   end
end

The above script creates a subject table with five records in each table.

Run the Migration

Now we have created all the migration files. Now we will execute all the migration files against the database. And To do so, open the command prompt and then go to the library directory where the application is located. And then type rake migrates as follows:

library> rake db: migrate

It will create a "schema_info" table only if it doesn't exist already. It will track the current version of the database every time a migration leads to a new version.

Rake is similar to Unix make program. It is advantageous as it makes complex tasks more accessible, like updating the database's structure.

Running Migrations for Production and Test Databases

If you want to specify the rails environment to use then write the code like following:

library> export RAILS_ENV = production
library> rake db:migrate
library> export RAILS_ENV = test
library> rake db:migrate
library> export RAILS_ENV = development
library> rake db:migrate

Instead of export Command, use "set RAILS_ENV = production" for Windows.

FAQs

  1. How are migrations stored?
    They are stored as files for each migration class.
     
  2. How do rails identify migrations internally?
    Internally, Rails uses the timestamp(migration's number) to identify them. 
     
  3. Name some of the column types supported by migrations?
    Some column types are binary, text, time, float, integer, date, datetime, etc.
     
  4. How do rails keep track of which migrations to run?
    They create a table called schema_migrations in the database to keep track of migration.

Key Takeaways

In this blog, we have learned what migrations in Ruby on rails are, their functions, supported data types, created them, run them.

Suppose you want to know about Controllers in Ruby on Rails, like what they are, how to create them, how to use them, etc. Then it would be best to refer to this blog here. You will get a whole idea about all this stuff and many more.

Recommended Readings:

Bus and Memory Transfer.

Live masterclass