1

I have to create a migration to do a db level validation. The migration:

 class DataBaseLevelValidation < ActiveRecord::Migration
  def change
    add_index :benefits_business_changes, [:benefit_id, :business_change_id], :unique => true
  end
end

The problem I have is that when I try to run rake db:migration I have this error:

Index name 'index_benefits_business_changes_on_benefit_id_and_business_change_id' on table 'benefits_business_changes' is too long; 
the limit is 62 characters/Users/mariocardoso/.rvm/gems/ruby-2.1.2/gems/activerecord-4.1.5/lib/active_record/connection_adapters/abstract/schema_statements.rb:797:in `add_index_options'

But if I change the name to a shorter version I get this:

SQLite3::SQLException: no such table: main.benefits_businessc: CREATE UNIQUE INDEX "index_benefits_businessc_on_benefit_id_and_business_change_id" ON "benefits_businessc" 

How can I overcome this problem?

The only ways I see, is to change the 'business_change' model to a shorter name (model, views, migration, ... everything).

There is any way to run this migration without having the error caused by the long name?

Mario
  • 1,213
  • 2
  • 12
  • 37

1 Answers1

8

You can do

add_index :benefits_business_changes, [:benefit_id, :business_change_id], :unique => true, :name => "a_shorter_name"

A common choice is to use just the first few letters of each column.

Frederick Cheung
  • 83,189
  • 8
  • 152
  • 174
  • Note that if you know about the index when creating the initial migration you can specify the index name directly in the `t.references` call -> http://stackoverflow.com/questions/28727240/migrations-t-references-doesnt-allow-index-name-to-be-specified . – Felix Aug 05 '15 at 07:13