Read more

Creating the inverse of a Rails migration

Arne Hartherz
February 27, 2012Software engineer at makandra GmbH

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.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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.

Posted by Arne Hartherz to makandra dev (2012-02-27 14:20)