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