59

I have the following in a migration:

create_table :model_with_a_long_name do |t|
  t.references :other_model_with_an_equally_long_name, index: true
end

That produces an index with too long of a name for Postgres.

Is there a way to manually specify the index name (without adding the integer column and the index separately)?

Something like the following:

create_table :model_with_a_long_name do |t|
  t.references :other_model_with_an_equally_long_name, index: true, index_name: 'model_and_other'
end

?

Drew Dara-Abrams
  • 8,016
  • 11
  • 40
  • 48
  • Possible duplicate of [How do I handle too long index names in a Ruby on Rails ActiveRecord migration?](https://stackoverflow.com/questions/5443740/how-do-i-handle-too-long-index-names-in-a-ruby-on-rails-activerecord-migration) – Jon Schneider Jan 04 '19 at 00:00

2 Answers2

140

According to Rails code for references, you can do so, providing index a Hash with options, the one you need called :name, so:

t.references :my_field, index: { name: 'my_index_name' }
chobo
  • 4,830
  • 5
  • 23
  • 36
Rustam Gasanov
  • 15,290
  • 8
  • 59
  • 72
1

Specify it longhand:

  t.integer :othermodel_id
  ...
end
add_index :thismodel, :othermodel_id, name: 'othermodel_index'
Community
  • 1
  • 1
Eric
  • 2,539
  • 18
  • 23