Rails migrations are contextual

So sometime ago i added a foreign key column as a rails migration which creates an index on that column as well: through the add_foreign_key method. This index is of the form rails_fk_some_hex  Unfortunately i forgot to add a unique constraint with the index which was a necessary use case.

I thought ‘no big deal’ i’ll just add that now, i ran:

add_index :table_name, :column_name, unique: true, index_name: :some_name

and viola it worked on my local machine like a charm. It even removed the previous index on that column that the foreign key migration created.

but running this on staging. I had 2 indexes, 1 unique and 1 non unique -_- .

Little debugging and i could confirm a pattern:

If these 2 migrations occur in the same rails db:migrate then the add_index migration also overwrites the index created by the foreign_key migration. However in different migrations, it just adds another index.


I’m not sure if this is a feature or a bug.  To solve for the cases where migrations run together(dev machines) or on servers where they are run separately I used remove_index if  index_exists? .


This isn’t something “breaking or a huge discovery”, just something weird i found in my Rails Journey and something you should be aware about.




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s