6

I'm looking to invoke another migration in a similar fashion to that of generators. Basically if you have a create table then at some point of time in the future you're no longer using the table and you want a migration to call up and down exactly opposite to those of the original create migration. If it's possible then I'd create a generator something like

rails g reverse_migration CreateModel

and then the result is something like

class ReverseCreateModel < ActiveRecord::Migration
  def up
    #call to create model down
  end
  def down
    #call to create model up
  end
end

I don't want any workaround kind of way and rather explicitly duplicate code and keep the ability for a clean migration and roleback.

Any help would be greatly appreciated!

Shrewd
  • 711
  • 5
  • 14

1 Answers1

12

A migration is just a Ruby file, so you can require it:

require "./db/migrate/20120117195557_create_model.rb"

class ReverseCreateModel < ActiveRecord::Migration
  def up
    CreateModel.new.down
  end

  def down
    CreateModel.new.up
  end
end

If your original migration uses change, you must use CreateModel.new.migrate(:down) and CreateModel.new.migrate(:up).

In my case, when using migrate(direction) generates more output when migrating:

==  ReverseCreateModel: migrating ======================================
==  CreateModel: reverting =============================================
(...)
==  CreateModel: reverted (0.0018s) ====================================

==  ReverseCreateModel: migrated (0.0019s) =============================

instead of:

==  ReverseCreateModel: migrating ======================================
(...)
==  ReverseCreateModel: migrated (0.0019s) =============================

This answer is based on https://stackoverflow.com/a/754316/183791

Community
  • 1
  • 1
dusan
  • 8,524
  • 2
  • 31
  • 54