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