Rolling back a failed Rails migration

后端 未结 9 769
一向
一向 2020-12-07 17:03

How do you roll back a failed rails migration? I would expect that rake db:rollback would undo the failed migration, but no, it rolls back the previous migratio

9条回答
  •  伪装坚强ぢ
    2020-12-07 17:59

    The easy way to do this is to wrap all of your actions in a transaction:

    class WhateverMigration < ActiveRecord::Migration
    
     def self.up
        ActiveRecord::Base.transaction do
    ...
        end
      end
    
      def self.down
        ActiveRecord::Base.transaction do
    ...
        end
      end
    
    end
    

    As Luke Francl noted, "MySql['s MyISAM tables don't] support transactions" -- which is why you might consider avoiding MySQL in general or at least MyISAM in particular.

    If you're using MySQL's InnoDB, then the above will work just fine. Any errors in either up or down will back out.

    BE AWARE some types of actions cannot be reverted via transactions. Generally, table changes (dropping a table, removing or adding columns, etc.) cannot be rolled back.

提交回复
热议问题