回滾交易

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