【问题标题】:Specify custom index name when using add_reference使用 add_reference 时指定自定义索引名称
【发布时间】:2015-08-02 16:23:34
【问题描述】:

我有以下迁移

class LinkDoctorsAndSpecializations < ActiveRecord::Migration
  def up
    add_reference :doctors, :doctor_specialization, polymorphic: true, index: true
  end

  def down
    remove_reference :doctors, :doctor_specialization, polymorphic: true
  end
end

当我运行 rake db:migrate 时出现错误

Index name 'index_doctors_on_doctor_specialization_type_and_doctor_specialization_id' on table 'doctors' is too long; the limit is 63 characters

那么在使用 add_reference 时如何指定索引名称,就像我们在 add_index :table, :column, :name =&gt; 'index name' 中指定的方式一样

【问题讨论】:

  • 你应该这样做add_index :table, :column, :name =&gt; 'index name'

标签: ruby-on-rails ruby ruby-on-rails-4 activerecord rails-migrations


【解决方案1】:

我不建议省略“add_reference”,但您可以省略“index”选项哈希键,然后使用“add_index”:

add_reference :table, :column
add_index :table, :column, :name => 'index_table_column'

或者,更合适的方式是这样的:

add_reference :doctors, :doctor_specialization, polymorphic: true, index: { name: 'index_doctors_doctor_specialization' }

【讨论】:

【解决方案2】:

正如我commented,做的:

add_index :table, :column, name: 'index name' 

这里是documentation。 或者,你可以试试这个:

class LinkDoctorsAndSpecializations < ActiveRecord::Migration
  def change
    add_reference :doctors, :doctor_specialization, polymorphic: true, index: { name: 'index name' }
  end
end

【讨论】:

  • 我建议强调答案的第二部分(将带有名称的哈希传递给索引:add_reference - 这似乎是使用add_indexan 的预期方式替代品。
【解决方案3】:

我听说解决此问题的最佳方法是将其排除在添加参考行之外并在下方手动指定它,就像在您问题的最后一行中一样

add_index :table, :column, :name => 'index name'

【讨论】:

    【解决方案4】:

    这实际上可行:

    add_index :table, :column, name: 'index name'
    

    Take a look 了解更多示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-28
      • 1970-01-01
      • 2013-04-17
      • 1970-01-01
      • 2020-07-25
      • 2016-05-25
      • 2019-01-01
      • 2018-06-20
      相关资源
      最近更新 更多