I have a model Booking that changes the status using AASM
models/booking.rb
before_validation :item_availability, if: -> { pending? || approved? }
enum status: [:pending, :approved, :rejected, :on_loan, :returned]
aasm column: :status, enum: true, whiny_transitions: true do
state :pending, initial: true
state :approved
event :approve do
transitions from: :pending, to: :approved
end
end
private
def item_availability
if quantity.to_f > item.quantity.to_f
errors.add(:base, "Not enough quantity for #{item.name} only #{item.quantity} left")
false
end
end
and I have a service that triggers the approve! event
def run
booking.transaction do
booking.approve!
booking.item.decrement!(:quantity, booking.quantity)
BookingsMailer.send_approval(booking).deliver_now
end
rescue ActiveRecord::RecordInvalid => e
errors.add(:base, e.message)
false
end
The problem here is the validation is being hit because the quantity is greater than the booking's quantity but the transaction in my service does not rollback.
According to documentation
Saving includes running all validations on the Job class. If whiny_persistence flag is set to true, exception is raised in case of failure.
I already set whiny_transitions to true but