【问题标题】:Rails state_machine - conditional validation?Rails state_machine - 条件验证?
【发布时间】:2011-10-25 15:34:39
【问题描述】:

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

【问题讨论】:

    标签: ruby-on-rails validation activerecord state


    【解决方案1】:

    感谢with_options,分组验证非常简洁。见here

    【讨论】:

      【解决方案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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-12-25
        • 2015-05-14
        • 1970-01-01
        • 2013-09-10
        • 2011-10-10
        • 1970-01-01
        相关资源
        最近更新 更多