简体   繁体   English

Rails state_machine-条件验证?

[英]Rails state_machine - conditional validation?

When using state_machine, how can you conditionally validate fields in the below way? 使用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

It seems to just ignore the if conditions and validate everything inside the state D: 似乎只是忽略if条件并验证状态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? 有没有一种很好的方法将它们整齐地包装在if块中?

Grouping validations thanks to with_options is really neat. 使用with_options分组验证确实很方便。 See here . 这里

Here's an example using the with_options for group validation. 这是一个使用with_options进行组验证的示例。

  with_options :if => :driver? do |driver|
    driver.validates_presence_of :truck_serial
    driver.validates_length_of :truck_serial, :maximum => 30
  end

  def driver?
    roles.any? { |role| role.name == "driver" }
  end 

Source: http://rubyquicktips.com/post/411400798/conditional-validation-using-with-options-to-improve 来源: http//rubyquicktips.com/post/411400798/conditional-validation-using-with-options-to-improve

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM