Rails state_machine - 条件验证?
使用 state_machine 时,如何通过以下方式有条件地验证字段?
state :unlit do
end
state :fire do
if is_big_fire?
validates_presence_of :big_log
end
if is_small_fire?
validates_presence_of :small_log
end
end
它似乎只是忽略 if 条件并验证状态 D 内的所有内容:
我想出的唯一某种解决方案是
validates_presence_of :big_log, :if => Proc.new { |fire| fire.is_big_fire? }
但是如果有更多验证,这就会变得疯狂。
validates_presence_of :big_log, :if => Proc.new { |fire| fire.is_big_fire? }
validates :fire_epicness_rating, :inclusion => { :in => %w(epic whowa RUNFORTHEHILLS) }, :if => Proc.new { |fire| fire.is_big_fire? }
etc
有没有一些好的方法可以将它们整齐地包装在 if 块中?
When using state_machine, how can you conditionally validate fields in the below way?
state :unlit do
end
state :fire do
if is_big_fire?
validates_presence_of :big_log
end
if is_small_fire?
validates_presence_of :small_log
end
end
It seems to just ignore the if conditions and validate everything inside the state D:
The only sort of solution I came up with was
validates_presence_of :big_log, :if => Proc.new { |fire| fire.is_big_fire? }
But this gets nuts if there are more validations.
validates_presence_of :big_log, :if => Proc.new { |fire| fire.is_big_fire? }
validates :fire_epicness_rating, :inclusion => { :in => %w(epic whowa RUNFORTHEHILLS) }, :if => Proc.new { |fire| fire.is_big_fire? }
etc
Is there some nice way of neatly wrapping these in if blocks?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通过
with_options
对验证进行分组非常简洁。请参阅此处。Grouping validations thanks to
with_options
is really neat. See here.下面是使用 with_options 进行组验证的示例。
来源:http://rubyquicktips.com/post/411400798 /条件验证使用带有选项来改进
Here's an example using the with_options for group validation.
Source: http://rubyquicktips.com/post/411400798/conditional-validation-using-with-options-to-improve