From Rails Guide
You can use Active Record's ability to rollback migrations using the revert
method:
require_relative '20100905201547_create_blocks'
class FixupCreateBlock < ActiveRecord::Migration
def change
revert CreateBlock
create_table(:apples) do |t|
t.string :variety
end
end
end
The revert
method also accepts a block of instructions to reverse. This could be useful to revert selected parts of previous migrations. For example, let's imagine that CreateBlock is committed and it is later decided it would be best to use Active Record validations, in place of the CHECK constraint, to verify the zipcode.
class DontUseConstraintForZipcodeValidationMigration < ActiveRecord::Migration
def change
revert do
# copy-pasted code from CreateBlock
reversible do |dir|
dir.up do
# add a CHECK constraint
execute <<-SQL
ALTER TABLE distributors
ADD CONSTRAINT zipchk
CHECK (char_length(zipcode) = 5);
SQL
end
dir.down do
execute <<-SQL
ALTER TABLE distributors
DROP CONSTRAINT zipchk
SQL
end
end
# The rest of the migration was ok
end
end
end
The same migration could also have been written without using revert but this would have involved a few more steps: reversing the order of create_table and reversible, replacing create_table by drop_table, and finally replacing up by down and vice-versa. This is all taken care of by revert.