AASM不会触发ActiveRecord :: Rollback

时间:2018-11-15 09:41:58

标签: ruby-on-rails aasm

我在预订模型中已批准事件枚举。我有一个before_validation可以批准

在我的 model / booking.rb 中,我添加了自定义验证

    include AASM

    before_validation :item_availability, if: :approved?

    enum status: [:pending, :approved, :rejected, :on_loan, :returned]

    aasm column: :status, enum: true do

       state :pending, initial: true
       state :approved
       state :rejected
       state :on_loan
       state :returned    

       event :approve do
         transitions from: :pending, to: :approved
       end

       event :reject do
         transitions from: :pending, to: :rejected
       end

       event :on_loan do
         transitions from: :approved, to: :on_loan
       end

       event :returned do
         transitions from: :on_loan, to: :returned
       end

  end


  private

  def item_availability
    if item.quantity.to_f < quantity.to_f
      errors.add(:base, "Not enough quantity for #{item.name} only #{item.quantity} left")
      false
    end
  end

在我的控制器中,我正在调用服务

 @service = Manage::BookingApprovalService.new({booking: @booking})
 @service.run

应用/服务/管理/ booking_approval_service

class Manage::BookingApprovalService < BaseService

  attr_accessor :booking

  def run
    Booking.transaction do
      booking.approve! // I confirmed that I'm getting the false here 
      booking.item.decrement!(:quantity, booking.quantity)
      BookingsMailer.send_approval(booking).deliver_now
    end
  end

end

调试 booking.approve!时,我变得虚假了,因为我预订的数量大于项目数量。

但是来自服务。递减!并且send_approval邮件仍在调用。

如果我因 booking.approve!

错误而无法回滚服务,为什么?

1 个答案:

答案 0 :(得分:1)

仅当您引发异常时,事务块才会回滚。

def run
  Booking.transaction do
    fail(ActiveRecord::Rollback) unless booking.approve! 
    booking.item.decrement!(:quantity, booking.quantity)
    BookingsMailer.send_approval(booking).deliver_now
  end
end

文档:https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html