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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)