If you would like to add your index without losing the data, you must create a new migration to add an index. Assuming your model is called Widget and the foreign model is called Zidget;
rails generate migration AddIndexToWidgets
and inside your new migration file at db/migrate/xxxxxxxxxx_add_index_to_widgets
class AddIndexToWidgets < ActiveRecord::Migration
def self.up
change_table :widgets do |t|
t.index :zidget_id # add ':unique => true' option if necessary
end
end
def self.down
change_table :widgets do |t|
t.remove_index :zidget_id
end
end
end
and then rake db:migrate
as usual and voilà, you have your indexed column.
Update: If adding an index is all you're doing, there is a more concise way to write the same thing. There is no difference regarding the results. It's just that the former syntax is meant to DRY your code if you have more than one change for your table.
class AddIndexToWidgets < ActiveRecord::Migration
def self.up
add_index :widgets, :zidget_id # add ':unique => true' option if necessary
end
def self.down
remove_index :widgets, :column => :zidget_id
end
end