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.
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.
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).
Yes, absolutely. A unique constraint creates a unique index.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With