December 31, 2022 By Matthew Rathbone *
On this page

In Ruby on Rails, a migration is a way to make changes to the database schema of your application. This could include creating new tables, modifying existing ones, or adding indexes to improve the performance of your queries.

One of the most common types of migration is the “add index” migration. Indexes are used to speed up the performance of certain types of queries by creating a separate data structure that stores the values from a specific column or set of columns, along with a pointer to the corresponding row in the table. This allows the database to quickly find the rows that match the criteria of a query, rather than having to search through the entire table.

To add an index to a table in Rails, you will need to create a new migration file. This can be done using the rails generate migration command, followed by the name of the migration and any additional arguments. For example, to add an index on the email column of the users table, you could run the following command:

rails generate migration add_index_to_users_email

This will create a new migration file in the db/migrate directory of your Rails application. Inside the file, you will see a class with a change method. This method is where you will define the instructions for modifying the database schema.

To add an index to the email column of the users table, you can use the add_index method provided by Rails. This method takes three arguments: the table name, the column or columns to be indexed, and any additional options. For example:

class AddIndexToUsersEmail < ActiveRecord::Migration[6.0]
  def change
    add_index :users, :email
  end
end

The add_index method can also accept additional options, such as the name of the index and whether it should be unique. For example:

class AddIndexToUsersEmail < ActiveRecord::Migration[6.0]
  def change
    add_index :users, :email, name: "index_users_on_email", unique: true
  end
end

Once you have defined your migration, you can run it using the rails db:migrate command. This will execute the instructions in the migration and apply the changes to the database schema.

It’s important to note that once you have run a migration, it cannot be undone. If you need to make changes to the schema later on, you will need to create a new migration to reverse the changes. This is why it’s a good idea to thoroughly test your migrations before running them in production.

In summary, Rails migrations are a powerful tool for modifying the database schema of your application. The add_index method can be used to add indexes to improve the performance of your queries, and migrations can be run using the rails db:migrate command. However, it’s important to carefully consider the impact of your migrations and thoroughly test them before running them in production.