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

时间:2015-05-21 06:41:08

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

我有以下迁移

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 => 'index name'中指定的那样

4 个答案:

答案 0 :(得分:45)

当我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

答案 1 :(得分:4)

这实际上有效:

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

Take a look了解更多示例。

答案 2 :(得分:1)

我不建议省略&#34; add_reference&#34;,但你可以省略&#34;索引&#34;选项哈希键然后使用&#34; add_index&#34;:

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' }

答案 3 :(得分:0)

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

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