使用 state_machine gem,我希望验证只在转换上运行。例如:
# Configured elsewhere:
# StateMachine::Callback.bind_to_object = true
class Walrus > ActiveRecord::Base
state_machine :life_cycle, :initial => :fetus do
state :fetus
state :child
state :adult
state :dead
event :coming_of_age do
transition :child => :adult
end
before_transition :child => :adult do
validate :coming_of_age_party_in_the_future
end
end
end
如果我将该验证附加到成人状态,则一旦该日期过去,它将失败。但我只需要它在过渡期间有效。我可以添加如下内容:
validate :coming_of_age_party_in_the_future, if: 'adult? && life_cycle_was == "child"'
但这似乎错过了过渡点。
另外,由于我在回调中绑定到对象,它如何有条件地调用“验证”,一个类方法?(绑定是必要的,因为回调中的许多方法都是私有的。)