Rails: Adding an index after adding column

user1611830 picture user1611830 · Apr 8, 2013 · Viewed 107.6k times · Source

Suppose I created a table table in a Rails app. Some time later, I add a column running:

rails generate migration AddUser_idColumnToTable user_id:string. 

Then I realize I need to add user_id as an index. I know about the add_index method, but where should this method be called? Am I supposed to run a migration (if yes, which one ?), then adding by hand this method?

Answer

Jaap Haagmans picture Jaap Haagmans · Apr 8, 2013

You can run another migration, just for the index:

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