How to Generate Migration in Ruby on Rails ?

Learn via video courses
Topics Covered

Overview

In Ruby on Rails, We create databases and tables to store data for the Rails application. When it comes to modification of existing database schema we have migrations to handle this problem. In this article, we will learn about migrations in Rails to modify the database schema.

Introduction to Migration in Rails

Migration in Ruby on Rails is a technique used to manage changes to a database structure over time. Migrations provide a structured and organized way to modify the database schema without writing SQL commands manually. In Rails, migrations are implemented as Ruby classes, which allow developers to make changes to the database schema through Ruby code, using the rails generate migrations command.

Since the ruby code is used to manage the database, that's why it becomes more secure to make changes in the data without disrupting the application's functionality. Migrations help keep the database schema in sync with the application code, which is especially important as the application evolves. As a result, migrations are a critical component of the Rails database workflow and are essential for maintaining the integrity and stability of the database over time.

Why we Need Migration in Rails

Let's say we want to build a web application using Ruby on Rails, we might need to work with databases to store our application data. When we're setting up our application, we'll need to create tables in our database to store the data using the rails generate migrations command.

Now, what happens if we need to make changes to those tables later on? Maybe we want to add a new column or change the data type of an existing column. We could manually update the database, but that can get messy and error-prone pretty quickly.

Rails migration is a way to manage changes to the database schema with time. Instead of updating the database directly, migrations allow us to write Ruby code that describes the desired changes to the schema. When we run the migration, rails first check the current version of the migration to the new migration. Then it runs sql commands to the database, line by line written in the migration file followed by updating the new migration version. This way our schema. rb file gets updated to new changes with the help of migrations. Hence, it provides consistency in schema changes and a reduction in errors that might arrive while updating the schema manually.

What can be done by Rails Migration

Rails migration provides many types of operations. Some of them are the following:

Rails Migration supports a wide range of data types that we can use to store data in our database. Here's a list of the basic data types that are supported:

How to Create a Migration

Let's create our first migration. Firstly, Navigate to the root directory of our rails application.

Now run the following command to generate an empty migration file.

This command will create a migration file (like 20220101010101_add_last_name_to_users.rb) and it will be stored in the db/migrate folder. We can edit this file to add the last_name to the users table.

How to Write a Migration

To write a migration file we need to use the change method provided by the migration file.

We can add code like add_column, remove_column, rename_column, and add_index to modify existing tables or create new ones, etc.

Let's say we put the following in our change method:

We added a column last_name to the users table with datatype as a string. When we write a migration file, we're describing the changes we want to make to the database schema, but we're not executing those changes yet.

Steps to Run Migration

We have successfullyy created and modified our migration file. But we need to sync the changes with our application. This can be done with the following command:

It is a command in Ruby on Rails that applies any pending migrations to the database. We need to run the rails db: migrate command to apply changes to the database schema.

How to Change Existing Migrations/Rollback Migrations

Sometimes, we might need to make changes to a migration file that we've already created. This could be because we made a mistake in the original migration or because we need to modify the migration to accommodate changes to our application. To modify an existing migration, we can use the following command to roll back the migration and make our changes.

Use the following command to reapply the migration.

For example, we have a migration that adds a new column last_name to our users table:

If we want to modify this migration to change the data type of the last_name column, we can create a new migration file that rolls back the original migration and applies our new changes:

Note: The up method is used to make the desired change, while we've also included the down method that uses change_column to roll back the migration and change the data type back to a string, in case we need to undo the change later.

Here, we've created a new migration that uses the change_column method to modify the data type of the last_name column from a string to text.

To apply the changes made by this migration, we first need to roll back the original migration that created the last_name column. We can do this using the rails db:migrate: down command, specifying the version of the original migration we want to roll back to.

Then we run the following command to apply the new migration:

Overall, changing the existing migrations or rolling back migrations in Rails Migration is a useful technique for managing changes to our database schema over time.

Examples for Understanding

Let's take an example of an E-commerce Rails application.

  • Creating a new table:

Here, we are creating a table named products(plural) with attributes such as name, description, price, quantity, and timestamps for having additional information like created_at and updated_at columns to track when the product was created and updated.

  • Adding a column to an existing table:

Here, we are adding one column named image_url to the products table with datatype as a string.

  • Modifying an existing column:

Here, we are changing the datatype of column price to decimal with a precision of 8 and a scale of 2. The up method makes this change and the down method reverts the change if required later on.

  • Dropping a table:

Here, We are dropping the table named reviews from the database if reviews are not required to be stored in the database.

FAQs

Q: What does Rails Migration serve, exactly?

A: The database schema can be modified using Rails Migration. It allows us to reversibly build and modify database tables and columns, change column types, add and remove indexes, and more.

Q: I have a non-SQL database, can I use Rails Migration on it?

A: SQL databases alone are what Rails Migration is made to deal with. For other kinds of databases, like MongoDB, equivalent tools are nevertheless accessible.

Q: What happens if I modify a migration file that has already been applied to the database?

A: It's not recommended to modify an existing migration file that has been applied already, as it can cause issues with the database schema. We should always create a new migration to modify the database schema and run it separately.

Conclusion

  • Migration in Ruby on Rails is a technique for controlling ongoing changes to a database structure.
  • Rails generate migration is used to generate an empty migration file.
  • To write a migration file we need to use the change method provided by the migration file.
  • The up method is used to make the desired change, while we've also included the down method that uses change_column to roll back the migration and change the data type back to a string, in case we need to undo the change later.