Add Downs A plugin for semi-automating the creation of migration 'down' methods. David A. Black April 2008 ==== This plugin adds a rake task, rake db:migrations:add_downs, which automatically writes down methods for your migrations. It does this by overriding a bunch of migration commands (add_column, rename_column, etc.). It then runs all your 'up' methods. The overridden commands figure out (as best they can) what you want the down equivalent to be, and print it out. The results are stored in RAILS_ROOT/tmp/migrations. You can, and should, examine them to make sure they're OK. You might see "UNKNOWN COLUMN TYPE!" in one or more instructions in the down method; that's because add_downs couldn't figure out, just from the migration file, what column type to add or change to. You have to fill those in by hand. Only migration files that already have a down method are processed. That will include any that are created automatically by Rails when you generate either a model or a migration. If the migration just contains the canonical "drop_table" down method, it will be processed and the method will simply be reconstituted. add_downs makes some pretty naive and non-heuristic assumptions about migration file naming -- namely, that it can chop off three characters at the beginning and end, and derive the correct class name from what's left. If you've got any non-vanilla naming going on, be warned. Nothing in db/migrate gets overwritten, though, so the worst that should happen is that it doesn't produce the right results. (But please back everything up first anyway!) Example ======= If you start with this, in db/migrate/001_add_downs_example.rb: class AddDownsExample < ActiveRecord::Migration def self.up create_table :examples do |t| t.string :text end add_column :examples, :number, :integer add_index :examples, :number rename_column :examples, :text, :body change_column :examples, :number, :float remove_column :examples, :text end def down end end and run this command: rake db:migrate:add_downs you'll end up with this in tmp/migrations/001_add_downs_example.rb: class AddDownsExample < ActiveRecord::Migration def self.up create_table :examples do |t| t.string :text end add_column :examples, :number, :integer add_index :examples, :number rename_column :examples, :text, :body change_column :examples, :number, :float remove_column :examples, :text end def down add_column :examples, :text, UNKNOWN COLUMN TYPE! change_column :examples, :number, UNKNOWN COLUMN TYPE! rename_column :examples, :body, :text remove_index :examples, :column => :number remove_column :examples, :number drop_table :examples end end That's about it. Comments and corrections welcome. Copyright (c) 2008, David A. Black (dblack@rubypal.com), released under the MIT license