migrations: t.references doesn't allow index name to be specified

Ruby on-RailsRuby

Ruby on-Rails Problem Overview


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

?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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

Solution 2 - Ruby on-Rails

Specify it longhand:

  t.integer :othermodel_id
  ...
end
add_index :thismodel, :othermodel_id, index_name: 'othermodel_index'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDrew Dara-AbramsView Question on Stackoverflow
Solution 1 - Ruby on-RailsRustam A. GasanovView Answer on Stackoverflow
Solution 2 - Ruby on-RailsEricView Answer on Stackoverflow