Ruby-on-rails 如何通过迁移向现有索引添加“唯一”约束

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20467165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:07:55  来源:igfitidea点击:

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

ruby-on-railspostgresql

提问by ironsand

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

如何unique: true向 Rails 数据库中现有的索引添加约束?

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

表 'editabilities' 上的索引名称 'index_editabilities_on_user_id_and_list_id' 已经存在

I'm using rails4 and postgresql.

我正在使用 rails4 和 postgresql。

回答by Baldrick

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

回答by asiniy

Faster way using add_index_options:

使用add_index_options 的更快方法:

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