我在我的Rails3应用程序中使用了Aaron Pfeifer的state_machine宝石 - 它仍然很漂亮。
我有一个事件,其结果在处理之前是未知的,我想根据结果设置以下状态。此处显示的“明显”方法不起作用:它会引发ArgumentError: :picked_many is not a known state value
错误。
根据事件的结果设置状态的正确方法是什么? (或者我只是想到这个错误?)
class MyModel < ActiveRecord::Base
state_machine :initial => :top do
event :pickanumber do
transition any => any
end
state :picked_zero
state :picked_one
state :picked_many
end
def pickanumber(n)
self.state = case n
when 0 then :picked_zero
when 1 then :picked_one
else :picked_many
end
super
end
end
和示例运行:
> m = MyModel.create
=> #<MyModel id: 26, state: "top", ...>
> m.pickanumber(2)
ArgumentError: :picked_many is not a known state value
答案 0 :(得分:1)
State在内部存储为字符串而不是符号。
这应该有用......
def pickanumber(n)
self.state = case n
when 0 then "picked_zero"
when 1 then "picked_one"
else "picked_many"
end
super
end