Rails: Adding an index after adding column Rails: Adding an index after adding column ruby-on-rails ruby-on-rails

Rails: Adding an index after adding column


You can run another migration, just for the index:

class AddIndexToTable < ActiveRecord::Migration  def change    add_index :table, :user_id  endend


If you need to create a user_id then it would be a reasonable assumption that you are referencing a user table. In which case the migration shall be:

rails generate migration AddUserRefToProducts user:references

This command will generate the following migration:

class AddUserRefToProducts < ActiveRecord::Migration  def change    add_reference :user, :product, index: true  endend

After running rake db:migrate both a user_id column and an index will be added to the products table.

In case you just need to add an index to an existing column, e.g. name of a user table, the following technique may be helpful:

rails generate migration AddIndexToUsers name:string:index will generate the following migration:

class AddIndexToUsers < ActiveRecord::Migration  def change    add_column :users, :name, :string    add_index :users, :name  endend

Delete add_column line and run the migration.

In the case described you could have issued rails generate migration AddIndexIdToTable index_id:integer:index command and then delete add_column line from the generated migration. But I'd rather recommended to undo the initial migration and add reference instead:

rails generate migration RemoveUserIdFromProducts user_id:integerrails generate migration AddUserRefToProducts user:references


Add in the generated migration after creating the column the following (example)

add_index :photographers, :email, :unique => true