将参数传递给 aasm 事件

Pass a parameter to aasm event

我正在使用 aasm 状态机。我有以下事件。它所做的是将状态从 order_created 更改为 payment_response_received。所以在改变这个之后我想调用一个方法verify_payment_response(data)。 我可以通过调用 @booking.move_to_payment_response_received! 来更改此状态,但是如何传递参数以供在后回调中使用?

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

您可以在触发事件之前将 data 分配给局部变量:

# 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

然后像这样在你的控制器中使用它:

@booking.payment_response_data = data
@booking.move_to_payment_response_received!
event(
  :move_to_payment_response_received, 
  after_commit: ->(data) { verify_payment_response(data) }
) { transitions from: :order_created, to: :payment_response_received }

然后将事件命名为: @booking.move_to_payment_response_received!(data)