使用 state_machine 进行条件验证
我正在使用 state_machine 构建一个多步骤表单,在转换到之前验证每个步骤的字段下一步。
这是我的模型:
class Foo < ActiveRecord::Base
state_machine :initial => :step1 do
event :next do
transition :step1 => :step2
transition :step2 => :step3
end
event :previous do
transition :step3 => :step2
transition :step2 => :step1
end
state :step1 do
validates_presence_of :field1
end
state :step2 do
validates_presence_of :field2
end
state :step3 do
validates_presence_of :field3
end
end
end
但是,这并没有按预期工作:
> f = Foo.new
=> #<Foo id: nil, field1: nil, field2: nil, field3: nil, state: "step1", created_at: nil, updated_at: nil>
Foo 初始化为“step1”状态。到目前为止,一切都很好。
> f.next
=> false
正如预期的那样,由于验证,过渡到下一步失败。
> f.errors.full_messages
=> ["Field2 can't be blank"]
但是,当我检查验证错误时,不是“Field1”未能按预期验证,而是“Field2”。它似乎正在对要转换到的状态而不是当前状态运行验证。
我做错了什么?
非常感谢。
I'm using state_machine to build a multi-step form, with fields for each step validated before transitioning to the next step.
This is my model:
class Foo < ActiveRecord::Base
state_machine :initial => :step1 do
event :next do
transition :step1 => :step2
transition :step2 => :step3
end
event :previous do
transition :step3 => :step2
transition :step2 => :step1
end
state :step1 do
validates_presence_of :field1
end
state :step2 do
validates_presence_of :field2
end
state :step3 do
validates_presence_of :field3
end
end
end
However, this isn't working as expected:
> f = Foo.new
=> #<Foo id: nil, field1: nil, field2: nil, field3: nil, state: "step1", created_at: nil, updated_at: nil>
Foo is initialised with a state of 'step1'. So far so good.
> f.next
=> false
Transitioning to the next step fails due to validation, just as expected.
> f.errors.full_messages
=> ["Field2 can't be blank"]
However, when I check for validation errors, it isn't 'Field1' that has failed to validate as expected, but rather 'Field2'. It appears to be running the validations for the state that is being transitioned to, rather than the current state.
What am I doing wrong?
Many thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
运行验证
我只是在这里猜测,但也许它在尝试转换到 step2 时
?也许您不需要在第一步进行验证,而是将所有验证移至一步:
I'm just guessing, here, but maybe it runs the validation in
when trying to transition to step2 ?
Perhaps you don't need a validation on step one, but rather move all the validations one step: