What is the best way to resolve Rails orphaned migrations?

I ended up solving the problem like this:

(1) Go to the branches that has the migration files and roll them back. This is not trivial when you have many branches which are will result in many conflicts if you try to merge them. So I use this commands to find out the branches of each orphan migration belongs to.

So, I need to find commit of the last time the migration was modified.

git log --all --reverse --stat | grep <LASTEST_ORPHAN_MIGRATION_ID> -C 10

I take the commit hash and determine which branch it belongs like this:

git branch --contains <COMMIT_HASH>

Then I can go back to that branch, do a rollback and repeat this process for all the missing files.

(2) Run migrations: checkout the branch you finally want to work on and run the migrations and you should be good to go.

Troubleshooting

I also ran in some cases where orphaned migrations where on deleted branches.

To solve this I created dummy migration files with the same migration_id of the missing files and roll them back. After that, I was able to delete they dummy migrations and have a clean migration status :)

Another alternative is deleting the missing files from the database directly (rails dbconsole):

delete from schema_migrations where version='<MIGRATION_ID>';

Migrations are stored in your database. If you want to remove the abandoned migrations, remove them from the db.

Example for Postgres:

  1. Open psql:

    psql
    
  2. Connect to your db:

    \c your_database
    
  3. If you're curious, display schema_migrations:

    SELECT * FROM schema_migrations;
    
  4. If you're curious, check if the abandoned migrations are present:

    SELECT version FROM schema_migrations WHERE version IN 
    ('20130320144219', '20130320161939', '20130320184628', '20130403190042',
     '20130403195300', '20130403214000', '20130410194222');
    
  5. Delete them:

    DELETE FROM schema_migrations WHERE version IN (<version list as above>);
    

Now if you run bundle exec rake db:migrate:status, you'll see the orphaned migrations have been successfully removed.