How to add `unique` constraint to already existing index by migration

How can I add unique: true constraint to already existing index in Rails database?

I tried to migrate by

  def change
    add_index :editabilities, [:user_id, :list_id], unique: true
  end

but migration fails with a error like this.

Index name 'index_editabilities_on_user_id_and_list_id' on table 'editabilities' already exists

I'm using rails4 and postgresql.


Solution 1:

Remove the old index and add it again with the new constraint:

def change
  remove_index :editabilities, [:user_id, :list_id]
  add_index :editabilities, [:user_id, :list_id], unique: true
end