Creating the inverse of a Rails migration

Let's say you need to revert a migration that happened a while back. You'd create a new migration that removes what was added back then in the up path, while its down path restores the old functionality.

While you could just copy&paste the down and up parts of it to the inverse part of the new migration, you may not want to do that. Especially when the up/down paths already contained some logic (that executed update statements on the created column, for example), copying does not feel right.

Someone already added the logic how to roll back the initial migration.\
So, in your new migration, just include the old one and call it:

require 'db/migrate/20120201031337_add_population_to_destinations'

class DropPopulationFromDestinations < ActiveRecord::Migration
  def self.up
    AddPopulationToDestinations.down
  end

  def self.down
    AddPopulationToDestinations.up
  end
end

Once multiple migrations tinkered with a database column, this probably is not the way to go and you are better off writing a "normal" migration.

Arne Hartherz About 12 years ago