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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)