Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 556
ironsand Avatar asked Dec 09 '13 09:12

ironsand


People also ask

How do I change unique index in PostgreSQL?

There is no way to change an index to unique index. You can see what you can change to index at alter index document. In this case you need to drop and create new unique index.

What is the difference between unique constraint and unique index?

A unique index ensures that the values in the index key columns are unique. A unique constraint also guarantees that no duplicate values can be inserted into the column(s) on which the constraint is created. When a unique constraint is created a corresponding unique index is automatically created on the column(s).

Does unique constraint create an index?

Yes, absolutely. A unique constraint creates a unique index.

Does unique constraint create index Postgres?

PostgreSQL automatically creates a unique index when a unique constraint or primary key is defined for a table. The index covers the columns that make up the primary key or unique constraint (a multicolumn index, if appropriate), and is the mechanism that enforces the constraint.


1 Answers

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 
like image 172
Baldrick Avatar answered Sep 19 '22 15:09

Baldrick