Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 

?

like image 685
Drew Dara-Abrams Avatar asked Feb 25 '15 18:02

Drew Dara-Abrams


People also ask

What is index in rails migration?

An index is used to speed up the performance of queries on a database. Rails allows us to create index on a database column by means of a migration. By default, the sort order for the index is ascending. But consider the case where we are fetching reports from the database.

Which command is used to to rollback migration in rails?

You must rollback the migration (for example with bin/rails db:rollback ), edit your migration, and then run bin/rails db:migrate to run the corrected version.

What is rails db reset?

rails db:reset:primary Drops and recreates the primary database from its schema for the current environment and loads the seeds. rails db:reset:secondary Drops and recreates the secondary database from its schema for the current environment and loads the seeds.


2 Answers

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' } 
like image 124
Rustam A. Gasanov Avatar answered Sep 19 '22 19:09

Rustam A. Gasanov


Specify it longhand:

  t.integer :othermodel_id   ... end add_index :thismodel, :othermodel_id, index_name: 'othermodel_index' 
like image 33
Eric Avatar answered Sep 22 '22 19:09

Eric