DRY Migrations (aka reverting or undoing earlier migrations)

I have a case where I made some database changes in migration 001 and now I want to undo them in migration 005. This is different that actually rolling back to version 001 (i.e. rake db:migrate version=1)...I actually want to undo or revert what I did in 001. The obvious thing to do would be to simply have 005 do the opposite of 001, but that isn't very DRY.

Using a simple example, let's say my migrations were:


  • 001_create_books.rb
  • 002_create_libraries.rb
  • 003_create_librarians.rb

and now my library is going electronic, so I do this:

  • 004_create_e_books.rb
  • 005_destroy_books.rb

In 005 I want to do the exact opposite of 001, so I did this:

class DestroyBooks < ActiveRecord::Migration
def self.up
CreateBooks::migrate(:down)
end

def self.down
CreateBooks::migrate(:up)
end
end

No comments: