What is the best way to resolve Rails orphaned migrations?

后端 未结 10 980
陌清茗
陌清茗 2020-12-22 22:29

I have been switching between branches in a project and each of them have different migrations... This is the scenario:

$ rake db:migrate:status

<
10条回答
  •  感动是毒
    2020-12-22 23:24

    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
    

提交回复
热议问题