我正在使用Rails-4.2.6
,state_machine-1.2.0和Ruby-2.3
我在Order模型上定义了状态机。如下
state_machine :status, initial: :initiated do
after_transition on: :succeeded, do: :oderable_success_callback
event :pending do
transition initiated: :pending
end
event :failed do
transition [:initiated, :pending] => :failed
end
event :succeeded do
transition [:initiated, :pending] => :succeeded
end
end
def oderable_success_callback
orderable.successful_payment
end
当我更新如下命令时,会触发after_transition回调。
order.succeeded
但是当我将订单更新为
时,它不会触发回调order.update(status: 'succeeded')
status
已更新为“succeeded
”,但无法触发回调。
如何在普通after_transition
上触发update
回调。
答案 0 :(得分:1)
order.update 不会触发after_transition回拨。如果要检测列的更改。您可以使用模型的after_update回调。
class Order < ActiveRecord::Base
after_update :tasks
def tasks
if(self.status_changed? && status == 'succeeded')
oderable_success_callback
end
end
end
答案 1 :(得分:0)
我有多个回调取决于状态,并避免多个if / else,我做了如下,
after_update :orderable_callback
state_machine :status, initial: :initiated do
event :pending do
transition initiated: :pending
end
event :failed do
transition [:initiated, :pending] => :failed
end
event :succeeded do
transition [:initiated, :pending] => :succeeded
end
state :pending do
def orderable_callback
orderable.pending_payment
end
end
state :failed do
def orderable_callback
orderable.failed_payment
end
end
state :succeeded do
def orderable_callback
orderable.successful_payment
end
end
end