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!
The up method is called when migrating “up” the database – forward in time – while the down method is called when migrating “down” the database – or, back in time. In other words, the up method is a set of directions for running a migration, while the down method is a set of instructions for reverting a migration.
Migration down and up You can run db:migrate:down and db:migrate:up with one command, which is db:migrate:redo . You can check if a specific migration is reversible. If not, ActiveRecord::IrreversibleMigration error will be raised.
To check for status, run rails db:migrate:status . Then you'll have a good view of the migrations you want to remove. Then, run rails db:rollback to revert the changes one by one. After doing so, you can check the status again to be fully confident.
Rails creates a table in your database called schema_migrations to keep track of which migrations have run. The table contains a single column, version . When Rails runs a migration, it takes the leading digits in the migration's file name and inserts a row for that "version", indicating it has been run.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With