What's the correct syntax for remove_index in a Rails 3.1.0 migration?

Solution 1:

For the record, the way to remove an index by name is

remove_index(:table_name, :name => 'index_name')

so in your case

remove_index(:users, :name => 'index_users_on_email')

Solution 2:

You can also remove the index specifying the columns, which from my point of view is less error prone than writing the name

remove_index :actions, :column => [:user_id, :action_name]

Solution 3:

Depending on the database type, you don't need to worry about removing the indexes in the self.down method since the index will automatically be removed from the database when you drop the column.

You can also use this syntax in your self.down method:

def self.down
   remove_column :users, :email
   remove_column :users, :encrypted_password
   remove_column :users, :reset_password_token
end

Solution 4:

I'd like to expand on @iWasRobbed's answer. If you have index on just single column then worrying about remove_index doesn't make sense since (just an assumtion!) the DB should be smart enough to cleanup the resources used by that index. But in case you have multiple columns index removing the column will reduce index to still existing columns, which is totally sensible thing to do, but kind of shows where you might want to use remove_index explicitely.

Just for illustration - migration below has that flaw that after being applied up and down it will leave the unique index on email (meaning the down part is not doing its job properly)

class AddIndexes < ActiveRecord::Migration
  def up
    add_column :users, :action_name, :string
    add_index  :users, [:email, :action_name], unique: true
  end

  def down
    remove_column :users, :action_name
  end
end

Changing the down block to

  def down
    remove_index :users, [:email, :action_name]
    remove_column :users, :action_name
  end

will fix that flaw and allow the migration to correctly return DB to the previous state with rake db:rollback