Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle too long index names in a Ruby on Rails ActiveRecord migration?

I am trying to add an unique index that gets created from the foreign keys of four associated tables:

add_index :studies,   ["user_id", "university_id", "subject_name_id", "subject_type_id"],   :unique => true 

The database’s limitation for the index name causes the migration to fail. Here’s the error message:

Index name 'index_studies_on_user_id_and_university_id_and_subject_name_id_and_subject_type_id' on table 'studies' is too long; the limit is 64 characters

How can I handle this? Can I specify a different index name?

like image 651
JJD Avatar asked Mar 26 '11 16:03

JJD


People also ask

What is an index in ActiveRecord?

A database index is an ordered data structure(read: another table)that we can create to help our database with some laborious searches.

What is index true in rails migration?

index: true vs foreign_key:true in migration When we write index: true to any column, it adds a database index to this column. Foreign key enforce referential integrity. In the example above we have profile_id column in educations table which is foreign key of profiles table.

How do I go down last migration in rails?

rails db:rollback:primary , where primary is the name of the database in your config/databases. yml file, to rollback the last migration. You can make usage of the STEPS attribute here, as usual. rails db:rollback:primary VERSION=your_migration_timestamp , to rollback only the provided migration version.


2 Answers

Provide the :name option to add_index, e.g.:

add_index :studies,   ["user_id", "university_id", "subject_name_id", "subject_type_id"],    unique: true,   name: 'my_index' 

If using the :index option on references in a create_table block, it takes the same options hash as add_index as its value:

t.references :long_name, index: { name: :my_index } 
like image 81
fl00r Avatar answered Sep 28 '22 03:09

fl00r


You can also change the index name in column definitions within a create_table block (such as you get from the migration generator).

create_table :studies do |t|   t.references :user, index: {:name => "index_my_shorter_name"} end 
like image 31
Craig Walker Avatar answered Sep 28 '22 04:09

Craig Walker