【问题标题】:Name an Index in a Migrate with index: true使用 index: true 在 Migrate 中命名索引
【发布时间】:2024-01-30 13:45:01
【问题描述】:

我有一个迁移,在下面,我用 index: true 创建了一个索引。但是,该索引的名称太长,因此我尝试自己命名。但是,这似乎没有运行。我得到相同的“名称太长”错误。有没有办法用 index: true 来命名这样的索引?如果不是,我该如何用 add_index 命名它?

class CreateVehicleProductApplicationNotes < ActiveRecord::Migration
  def change
    create_table :vehicle_product_application_notes do |t|
      t.references :product_id, index: true
      t.references :product_application_id, index: true, :name "my_index"
      t.references :note_id, index: true

      t.timestamps
    end
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby indexing naming


    【解决方案1】:

    您可以传递包含索引名称的Hash,而不是true,如下所示,

    t.references :product_application_id, index: { name: "my_index" }
    

    参考: http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html

    【讨论】: