Rails state_machine - 条件验证?

时间:2011-10-25 15:34:40

标签: ruby-on-rails validation activerecord state

使用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块中?

2 个答案:

答案 0 :(得分:3)

归功于with_options的分组验证非常简洁。请参阅here

答案 1 :(得分:2)

以下是使用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 

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