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