How to minimize migration files in rails

A few days back, while reviewing a PR of one of my colleagues I saw there were around 9-10 migration files of which 2 were of new table addition and the remaining were column addition to the table. Ideally, this should not happen but this is not an ideal world, we may forget to include few columns and add them later. This is fine but my point is why can’t we roll back the changes and fix the 1st migration file itself by adding a column, we are just developing not gone live yet.

Today I faced a similar problem, as per my ideology I tried to roll back with

rake db:rollback

but this was falling, again and again, Spent around 30 mins and gave up and tried to do it manually.

I dropped the tables using PgAdmin, which can be done using any other DB viewer then added the columns to the 1st script and ran migration but my migration didn’t run because as per RoR these scripts are already been executed even after I removed the tables.

So the question rises? How RoR knows that which migration has been run and which is pending.

The answer is RoR maintains a table schema_migrations which maintains the version which has been run till now. So I deleted the versions which I ran recently.

delete from schema_migrations where version in ('20210914112546','20210914113808','20210914115220')

Voila!! New Column has been added, 0 new files added to the PR.

Update 15/09/2021

Found a new way, in this you don’t have to delete the version from the database. The idea is to add a new migration to add a column, once done delete the file, and add the column to create table migration file. In this way, there will be only one file and the changes will also be available on your database.

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *