使用add_reference时指定自定义索引名称

bha*_*anu 16 ruby activerecord ruby-on-rails rails-migrations ruby-on-rails-4

我有以下迁移

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
Run Code Online (Sandbox Code Playgroud)

当我跑,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 => 'index name'

Aru*_*hit 48

正如我评论的那样,做:

add_index :table, :column, name: 'index name' 
Run Code Online (Sandbox Code Playgroud)

这是文档.或者,你可以试试这个:

class LinkDoctorsAndSpecializations < ActiveRecord::Migration
  def change
    add_reference :doctors, :doctor_specialization, polymorphic: true, index: { name: 'index name' }
  end
end
Run Code Online (Sandbox Code Playgroud)

  • 我建议强调您答案的第二部分(将带有名称的哈希传递给 index: 在 `add_reference` 中 - 这似乎是使用 `add_index` 替代方法的预期方法。 (3认同)

And*_*eko 5

这实际上会起作用:

add_index :table, :column, name: 'index name'
Run Code Online (Sandbox Code Playgroud)

查看更多示例。