Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index name too long on rails activerecord migration. Tried adding index manually, same error

So I've been successfully creating join tables by using the name parameter when adding an index, but I'm not sure why this isn't working when I'm trying to do create a new migration:

class CreateVMailCampaignScheduleHours < ActiveRecord::Migration[5.1]
  def change
    create_table :v_mail_campaign_schedule_hours do |t|
      t.belongs_to :v_mail_campaign_schedule, foreign_key: true
      t.string :day
      t.time :start_hours
      t.time :stop_hours

      t.timestamps
    end
    add_index [:v_mail_campaign_schedule_hours, :v_mail_campaign_schedule_id], name: :v_mail_campaign_schedule_id
  end
end

The error I get is:

ArgumentError: Index name 'index_v_mail_campaign_schedule_hours_on_v_mail_campaign_schedule_id' on table 'v_mail_campaign_schedule_hours' is too long; the limit is 64 characters

Any suggestions? I thought my add_index would do the trick, but apparently not.

like image 437
LewlSauce Avatar asked Nov 16 '25 07:11

LewlSauce


2 Answers

You can change it to the following:

class CreateVMailCampaignScheduleHours < ActiveRecord::Migration[5.1]
  def change
    create_table :v_mail_campaign_schedule_hours do |t|
      t.bigint :v_mail_campaign_schedule
      t.string :day
      t.time :start_hours
      t.time :stop_hours

      t.timestamps
    end
    add_index :v_mail_campaign_schedule_hours, :v_mail_campaign_schedule_id, name: :index_campaign_schedule_hours_on_schedule
  end
end

Your approach to create the index manually is the right one. However, t.belongs_to, which is an alias for t.references, instructs the creation of both the foreign key column and the corresponding index. So Rails still tries to create the index, before reaching add_index. Using a simple t.bigint doesn't create the index.

like image 94
Matthieu Libeer Avatar answered Nov 17 '25 22:11

Matthieu Libeer


Yeah, so as previously said, t.belongs_to will create an index.

So, I think you can still use create_join_table, but you'll just need to specify index: false on your belongsTo.

create_join_table :v_mail_campaign_schedule_hours do |t|
  t.belongs_to :v_mail_campaign_schedule, foreign_key: true, index: false
  t.string :day
  t.time :start_hours
  t.time :stop_hours

  t.timestamps
  t.index [:v_mail_campaign_schedule_id], name: 'v_mail_campaign_schedule_id'
end
like image 29
Josh Paul Avatar answered Nov 17 '25 20:11

Josh Paul