【问题标题】:How to remove index in rails如何删除rails中的索引
【发布时间】:2014-03-30 15:19:37
【问题描述】:

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


    【解决方案1】:

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

    remove_index :completions, name: "index_completions_on_survey_id_and_user_id"
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 这不会将其从 schema.rb 中删除。
      【解决方案3】:

      您可以将列名提供给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 的示例:

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

      remove_index :accounts, :branch_id
      

      或者

      remove_index :accounts, column: :branch_id
      

      如果只存在一个这样的索引,则删除accounts表中branch_id和party_id上的索引。

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

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

      remove_index :accounts, name: :by_branch_party
      

      除此之外,你还可以这样做:

      remove_index :accounts, %i[branch_id party_id]
      

      【讨论】:

        【解决方案4】:

        这里接受的答案在需要回滚迁移时不起作用,会报ActiveRecord::IrreversibleMigration错误。

        remove_index 只有在给定 :column 选项时才可逆。

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

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

        【讨论】:

          猜你喜欢
          • 2016-02-02
          • 1970-01-01
          • 2017-12-29
          • 1970-01-01
          • 2014-09-11
          • 1970-01-01
          • 1970-01-01
          • 2019-03-06
          • 2018-09-20
          相关资源
          最近更新 更多