Rails state_machine - 条件验证?

发布于 2024-12-11 17:15:51 字数 730 浏览 0 评论 0原文

使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧人九事 2024-12-18 17:15:51

通过 with_options 对验证进行分组非常简洁。请参阅此处

Grouping validations thanks to with_optionsis really neat. See here.

秋心╮凉 2024-12-18 17:15:51

下面是使用 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 /条件验证使用带有选项来改进

Here's an example using the with_options for group validation.

  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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文