如何删除导轨中的索引

问题描述 投票:0回答:4

我发现我的架构中有两个“survey_id”列,这给我带来了一些问题。具体来说,我需要删除第二个索引,因为我不希望 Survey_id 是唯一的。

 add_index "completions", ["survey_id"], name: "index_completions_on_survey_id"
 add_index "completions", ["survey_id"], name: "index_completions_on_survey_id_and_user_id", unique: true

我已经尝试过了

def change
  remove_index "completions", ["survey_id"], name => "index_completions_on_survey_id_and_user_id"
end

def change
  remove_index "completions", ["survey_id"], name: "index_completions_on_survey_id_and_user_id"
end

但这些似乎都不起作用。此迁移删除索引的正确语法是什么?我觉得这是基本的,我只是错过了一些东西。

ruby-on-rails rails-activerecord
4个回答
134
投票

删除一列时,您不提供索引中的列。尝试:

remove_index :completions, name: "index_completions_on_survey_id_and_user_id"

26
投票

当您需要回滚迁移时,此处接受的答案不起作用,将会给出

ActiveRecord::IrreversibleMigration
错误。

仅当提供

remove_index

 选项时,
:column
才是可逆的。

def change
  remove_index "completions", column: [:survey_id], name: "index_completions_on_survey_id_and_user_id"
end

这将删除索引并且也是可逆的。


13
投票

从 Rails 控制台,运行以下

ActiveRecord::Migration.remove_index "completions", name: "index_completions_on_survey_id_and_user_id"

9
投票

您可以向

remove_index
提供列名称。
remove_index
方法将
table_name
options
作为参数。通过传入索引名称的选项,通过
index_name_for_remove
私有方法确定,这很简单(如果它是一个数组):

...
column_names = Array(options).map(&:to_s)
...

if column_names.any?
  checks << lambda { |i| i.columns.join('_and_') == column_names.join('_and_') }
end

来自 API 文档的示例

删除账户表中的branch_id索引(如果恰好存在一个这样的索引)。

remove_index :accounts, :branch_id

或者

remove_index :accounts, column: :branch_id

删除账户表中的branch_id和party_id索引(如果恰好存在一个这样的索引)。

remove_index :accounts, column: [:branch_id, :party_id]

删除账户表中名为 by_branch_party 的索引。

remove_index :accounts, name: :by_branch_party

除了上述之外,你还可以这样做:

remove_index :accounts, %i[branch_id party_id]
© www.soinside.com 2019 - 2024. All rights reserved.