跳至內容 跳至搜尋

ActiveRecord::Base.transaction 使用此例外情況來區分蓄意回滾與其他例外情況。通常,引發例外情況會導致 .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
      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