How to solve: Rails db:migration files accidentally deleted

Last week I was working on different topics in different branches. I have to admit that one of my main problem while coding is that I forget to create new branches constantly. What happened last week was that I wanted to work in an issue that required a rails migration to create a new field to a database. I did it and then realized I was in the wrong branch. So I deleted the db file in charge of that migration.

Once I cleant my git mess and I continue working on the topic, I realized that in order to commit those changes to master, I needed the file I had deleted.

This is the typical problem that would have taken me ages to fix if I didn’t have a mentor. And I think it’s one of the main problems of underrepresented people in Tech. Due to our Imposter Syndrome (and my juniority) sometimes I am afraid of asking things so the people realize I don’t deserve the place where I am. It took me ages (in fact, the same time it required me to start seriously coding) to realize that I questions are not dumb, neither is not knowing some basics. Having some holes in the overview picture it’s totally legit, and something that I think it will happen my whole professional life (and also personal, but that’s another story).

So I have decided to also post sometimes the solution to these kinds of problems just in case someone is also in my situation and doesn’t have a mentor around, lives in a place with a lack of user groups or is afraid of stack overflow.

What we did:

First, I recreated the same file again, by writing the following command in my terminal:

rails generate migration AddDefaultCourseTypeToCampaigns default_course_type:string

(The regular syntax for rails migrations: rails generate migration Add{fieldName}To{TableName} field_name:type)

So I had again this file in my local git and I could push it to the remote git.

So a new problem appeared, as the version of this file was not matching the database version, as it was imposible to migrate. After I tried to run rails db:migrate I was getting the following error:

This was preventing me from being able to run my local environment and my first guess would have been to delete the file again. But in order to have a mirrored local and remote environment, we needed to add the ID of this file to the migrations table in the database.

So I run the following mysql commands in my machine:

USE database_name;

SELECT * FROM schema_migrations;

INSERT INTO schema_migrations VALUES (‘ID’);

This ID is the number that appears in the filename.

After I exited mysql and run rails db:migrate again. I didn’t get any error, so this gave me the possibility to push the files to my remote git so both were synchronized.

And this was it! I know it may sound a bit obvious to some people but it would have taken me hours to understand what the problem was and specially how to solve it.