Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to resolve Rails deleted migrations?

I happened to have deleted migrations and I don't want to revert these removed migrations.

This is what rake db:migrate:status produces:

 Status   Migration ID    Migration Name
------------------------------------------------------

   up     0               ********** NO FILE *********
   up     20150209023430  Create users 
   up     20150320184628  ********** NO FILE **********
   up     20150322004817  Add roles to users
   up     20150403190042  ********** NO FILE **********

rake db:migrate and rake db:rollback commands won't work because of the missing files.

I have no intentions to lose my data, so I don't want to use rake db:drop or rake db:reset.

What can I do to be able to perform migrate and rollback and how to get rid of the missing files?

like image 586
Alex Shmatko Avatar asked Jun 08 '16 09:06

Alex Shmatko


People also ask

What happens if I delete migrations?

Deleting migration files means losing your history. This historical info is recorded in the django_migrations table in your database. if you delete migration files, you will get dependency errors. So Don't try to lose your history by deleting your migration files.

How do I roll back irreversible migration rails?

You can't reverse an irreversible migration. So, if the migration is Down and you want it to migrate Up just comment the contents in up method and run the migration again. Save this answer.

How do you rerun all migrations in rails?

just use rake db:reset , that will drop your database (same as undoing all migrations) and reset to the last schema. UPDATE: a more correct approach will be using rake db:migrate:reset . That will drop the database, create it again and run all the migrations, instead of resetting to the latest schema.


2 Answers

Alexander, you can get rid of those non-existing migrations. when you do rake db:migrate:status it will show as in the question.

so you can manually delete those versions from schema_migrations table using a pure sql query.

delete from schema_migrations where version = <version_number> by executing above query, it will be resolved.

like image 105
Kushal Avatar answered Nov 07 '22 09:11

Kushal


If you can find the migration's timestamp - the number part of the filename, then you can do:

rake db:migrate:down VERSION=20100905201547

You can find the timestamp using rake db:migrate:status

Edit - when the migration file has been irrecoverably deleted

You can get around this by creating an empty migration file, migrating, then rolling back twice. Then, make sure you delete the empty migration file before migrating again.

$ bundle exec rails g migration fix_rollback_error
$ bundle exec rails db:migrate
$ bundle exec rails db:rollback STEP=2
$ rm db/migrate/20200217040302_fix_rollback_error.rb
$ bundle exec rails db:migrate
like image 21
Kaka Ruto Avatar answered Nov 07 '22 10:11

Kaka Ruto