How to fix the Index name too long error in rails migrations
Today, I was reviewing some legacy code, trying to isolate the bottlenecks and pinpoint the optimisation strategies for scaling and performance optimisations of a rails app.
As the usual procedure, I wanted to check the database indexes and see if something was missing here. And my guess was in the right direction. Some of the indexes were missing.
So the next obvious thing to do:
Create a migration for adding the missing indexes.
I thought it was gonna be a breeze, I generated the migration, filled the migration file with the correct table name and fields etc, but when I tried to run the migration, I stumbled upon an issue.
ArgumentError: Index name 'index_loan_application_status_message_template_groups_on_message_template_group_id' on table 'loan_application_status_message_template_groups' is too long; the limit is 63 characters
Problem: The index name is too long
So here is what my migration looked like:
class IndexForeignKeysInLoanApplicationStatusMessageTemplateGroups < ActiveRecord::Migration def change add_index :loan_application_status_message_template_groups, :message_template_group_id end end
After a bit of googling I learned that PostgreSQL has a limit of 63 char for naming, as can be found here.
So I need to keep my index identified under 63 chars.
And our nice folks who build rails/active record have given us a nice way to accomplish this.
Solution: You can specify the name of the index and keep it under the 63 chars mark by passing values to the
name argument in your migration.
So I modified my migration to the following:
class IndexForeignKeysInLoanApplicationStatusMessageTemplateGroups < ActiveRecord::Migration def change add_index :loan_application_status_message_template_groups, :message_template_group_id, name: 'loan_application_status_message_template_group_index' end end
Hope that helps someone. :)