ruby-on-railsrubystate-machineaasm

Pass a parameter to aasm event


I am using aasm statemachine. I have the below event. What this does is changes the state from order_created to payment_response_received. So after changing this I want to call a method verify_payment_response(data). I can make this state change by calling @booking.move_to_payment_response_received! , but how can I pass parameters for use in the after callback?

event :move_to_payment_response_received do
  after_commit do
         self.verify_payment_response(data) #How can I pass this data param from my controller
  end
  transitions from: :order_created, to: :payment_response_received
end

Solution

  • You can assign the data to a local variable before firing the event:

    # in your model
    
    attr_accessor :payment_response_data
    
    event :move_to_payment_response_received, :after_commit => :verify_payment_response do
      transitions from: :order_created, to: :payment_response_received
    end
    
    private
    
    def verify_payment_response
      data = payment_response_data
    
      # already existing code to verify `data`
    end
    

    And use this in your controller like this:

    @booking.payment_response_data = data
    @booking.move_to_payment_response_received!