I have been switching between branches in a project and each of them have different migrations... This is the scenario:
$ rake db:migrate:status
<
Here's a rake task I wrote for this purpose. It invokes the same method that the db:migrate:status
uses under the hood, ActiveRecord::Base.connection.migration_context.migrations_status
# lib/tasks/cleanup_migration_entries.rake
desc 'Removes schema_migration entries for removed migration files'
task 'db:migrate:cleanup': :environment do
migration_context = ActiveRecord::Base.connection.migration_context
versions_to_delete =
migration_context.migrations_status
.filter_map { |_status, version, name| version if name.include?('NO FILE') }
migration_context.schema_migration.delete_by(version: versions_to_delete)
puts "Cleaned up #{versions_to_delete.size} orphaned migrations."
end
Here is a rake version of the psql answer from @medik, which won't erase your db or do anything crazy:
1) Find your orphaned migration versions:
rails db:migrate:status
2) Note the versions of the missing migrations and head into the db console:
rails dbconsole
3) Now remove the versions from the migration table manually:
delete from schema_migrations where version='[version_number]';
Migrations are stored in your database. If you want to remove the abandoned migrations, remove them from the db.
Example for Postgres:
Open psql:
psql
Connect to your db:
\c your_database
If you're curious, display schema_migrations:
SELECT * FROM schema_migrations;
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');
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.
You could merge the two branches back into the master so that you have all migrations available. If you really don't want those migrations there, but want to be able to roll back, you could edit the schema_migrations table in your database to remove the rows corresponding to the migrations for which you don't have files. However, this will cause problems if you then switch to another branch with different migrations.