回滚交易

ActiveRecord::Base.transaction 使用 ActiveRecord::Rollback 异常来区分故意回滚与其他异常情况。通常,引发异常将导致 .transaction 方法回滚数据库事务并传递异常。但是如果你提出了 ActiveRecord::Rollback 异常,那么数据库事务将被回滚,而不会传递异常。

例如,你可以在控制器中执行此操作以回滚事务:

class BooksController < ActionController::Base
  def create
    Book.transaction do
      book = Book.new(params[:book])
      book.save!
      if today_is_friday?
        # The system must fail on Friday so that our support department
        # won't be out of job. We silently rollback this transaction
        # without telling the user.
        raise ActiveRecord::Rollback, "Call tech support!"
      end
    end
    # ActiveRecord::Rollback is the only exception that won't be passed on
    # by ActiveRecord::Base.transaction, so this line will still be reached
    # even on Friday.
    redirect_to root_url
  end
end