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.
Solution:
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?
.
Conclusion:
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.