Rails嵌套with_option:如果在验证中使用 [英] Rails nested with_option :if used in validation

查看:72
本文介绍了Rails嵌套with_option:如果在验证中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

validate :updatable?  # First validation there is
with_options :if => Proc.new { |object| object.errors.empty? } do |updatable|
    updatable.with_options :if => "self.current_step == basic" do |step|
        validates .... bla-bla bla

因此,在进行任何验证之前,将调用 updatable 子例程,该子例程将在errors[:base]数组中填充适当的错误,这意味着该对象不可更新.如果此子例程中发现任何错误,我希望它跳过其余的验证,但是上述示例有效-它执行所有验证.

So, before any validations are made, the updatable subroutine is called and it populates the errors[:base] array with appropriate errors, meaning that object is not updatable. And I wanted it to skip the rest of the validations if any errors are found in this subroutine, but abovementioned example is NOT working - it performs all the validations.

但是,如果我将:if => "self.current_step == basic"更改为:if => "self.errors.empty? && self.current_step == basic"的话,它就像是一种魅力.

But, if I change :if => "self.current_step == basic" to :if => "self.errors.empty? && self.current_step == basic" is works like a charm.

我做错了什么?示例显示,嵌套的with_option应该有效.

What I'm doing wrong ? Examples show, that nested with_option should work.

有人可以帮助我吗?预先感谢.

Can someone help me ? Thanks in advance.

推荐答案

您是正确的,当嵌套两个:if条件时,内部的将替换外部的,并始终进行检查.处理两个嵌套级别的解决方法是:

You are right that when nesting two :if conditions, the inner one will replace the outer one and always be checked. A workaround to handle two levels of nesting is:

with_options :unless => !(outer condition) do
  with_options :if => (inner condition) do

if和除非条件不会相互覆盖.我不确定我是否将其称为错误,但是如果您可以嵌套多个:if条件,那就太好了.

The if and unless conditions do not overwrite each other. I'm not sure I would call this a bug, but it would be nice if you could nest multiple :if conditions.

这篇关于Rails嵌套with_option:如果在验证中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆