How to add an index in rails?

less than 1 minute read

Syntax

add_index(table_name, column_name, **options)

Example

Add an index to the email column in the users table.

add_index :users, :email

Add a uniq index to the email column in the users table.

add_index :users, :email, unique: true

Rails Command:

$ rails generate migration add_index_to_users email:index
      invoke  active_record
      create    db/migrate/20240801141018_add_index_to_users.rb

The above command will generate the following migration. You may need to delete the add_column line if the column already exists.

class AddIndexToUsers < ActiveRecord::Migration[7.1]
  def change
    add_column :users, :email, :string
    add_index :users, :email
  end
end

References