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