如何通过迁移向现有索引添加`unique`约束 [英] How to add `unique` constraint to already existing index by migration
本文介绍了如何通过迁移向现有索引添加`unique`约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Rails数据库中已存在的索引中添加 unique:true
约束?
How can I add unique: true
constraint to already existing index in Rails database?
我试图
def change
add_index :editabilities, [:user_id, :list_id], unique: true
end
但迁移失败并出现类似这样的错误。
but migration fails with a error like this.
表
'editabilities'上的索引名'index_editabilities_on_user_id_and_list_id'已经存在
Index name 'index_editabilities_on_user_id_and_list_id' on table 'editabilities' already exists
我正在使用rails4和postgresql。
I'm using rails4 and postgresql.
推荐答案
删除旧索引,并使用新约束再次添加它:
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
这篇关于如何通过迁移向现有索引添加`unique`约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文