如何删除rails中的索引

Tom*_*ond 25 ruby-on-rails

我发现我的架构中有两个"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
Run Code Online (Sandbox Code Playgroud)

我试过了

def change
   remove_index "completions", ["survey_id"], name => "index_completions_on_survey_id_and_user_id"
 end
Run Code Online (Sandbox Code Playgroud)

def change
   remove_index "completions", ["survey_id"], name: "index_completions_on_survey_id_and_user_id"
 end
Run Code Online (Sandbox Code Playgroud)

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

vee*_*vee 42

删除索引时,不提供索引中的列.尝试:

remove_index "completions", name: "index_completions_on_survey_id_and_user_id"
Run Code Online (Sandbox Code Playgroud)


小智 27

当您需要回滚迁移时,此处接受的答案不起作用,将会出现ActiveRecord::IrreversibleMigration错误。

remove_index仅当有选项时才是可逆的:column

def change
  remove_index "completions", column: [:survey_id], name: "index_completions_on_survey_id_and_user_id"
end
Run Code Online (Sandbox Code Playgroud)

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


小智 13

从 Rails 控制台,运行以下命令

ActiveRecord::Migration.remove_index "completions", name: "index_completions_on_survey_id_and_user_id"
Run Code Online (Sandbox Code Playgroud)

  • 但这并没有将其从 schema.rb 中删除。 (4认同)

Sye*_*lam 5

您可以向 提供列名remove_index。该remove_index方法将table_nameoptions作为参数。索引名称中传递的选项是通过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
Run Code Online (Sandbox Code Playgroud)

API 文档中的示例:

如果恰好存在一个这样的索引,则删除帐户表中 branch_id 上的索引。

remove_index :accounts, :branch_id
Run Code Online (Sandbox Code Playgroud)

或者

remove_index :accounts, column: :branch_id
Run Code Online (Sandbox Code Playgroud)

如果恰好存在一个这样的索引,则删除帐户表中 branch_id 和 party_id 上的索引。

remove_index :accounts, column: [:branch_id, :party_id]
Run Code Online (Sandbox Code Playgroud)

删除accounts 表中名为by_branch_party 的索引。

remove_index :accounts, name: :by_branch_party
Run Code Online (Sandbox Code Playgroud)

除了上述,你可以只做:

remove_index :accounts, %i[branch_id party_id]
Run Code Online (Sandbox Code Playgroud)