Adding indexes to columns in rails migration

I tried to add an index to a column and failed. After digging deeper these are my findings.

In rails migration if we want to add index to a column there are 2 ways.

  • While creating a new table you can specify
    index: true

eg:

def change
  create_table :users do |t|
    t.string :name, limit: 30, null: false
    t.string :password, null: false, limit: 20
    t.string :email, null: false, limit: 20, index: true
  end
  • In all the remaining scenarios(add/update new column) we need to explicitly mention
    add_index

eg:

def change
  add_column :users, :employee_number, :integer
  add_index :users, :employee_number
end

index: true works only when creating new table. Hoping this is helpful.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.