ruby-on-rails 如何删除导轨中的索引

m0rkklqb  于 2022-11-19  发布在  Ruby
关注(0)|答案(4)|浏览(160)

我发现我的模式中有两个“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

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

dwthyt8l

dwthyt8l1#

删除索引时未提供索引中的列。请尝试:

remove_index :completions, name: "index_completions_on_survey_id_and_user_id"
ajsxfq5m

ajsxfq5m2#

当您需要回滚迁移时,此处可接受的答案不起作用,将给出ActiveRecord::IrreversibleMigration错误。
remove_index仅在给定:column选项时可逆。

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

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

fnatzsnv

fnatzsnv3#

从Rails控制台运行以下命令

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

gtlvzcf84#

您可以将列名提供给remove_indexremove_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

API documentation示例:
删除accounts表中分支_id上的索引(如果正好存在一个这样的索引)。

remove_index :accounts, :branch_id

或者

remove_index :accounts, column: :branch_id

删除帐户表中分支_id和party_id上的索引(如果正好存在一个这样的索引)。

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

删除帐户表中名为by_分支_party的索引。

remove_index :accounts, name: :by_branch_party

除了以上所述,您还可以执行以下操作:

remove_index :accounts, %i[branch_id party_id]

相关问题