用:if验证 [英] Validates with :if

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

问题描述

我正在尝试创建一个条件,其中属性一为零,属性二为一,那么模型无效。但是当我输入:

I'm trying to create a condition in which the attribute 'one' is zero and the attribute 'two' is one, then a model is not valid. But when I make:

Model.create(:one => 1, :two => 0).valid?

单元测试返回 true !为什么?

The unit test returns true! Why?

validates :one, :two, :presence => true, :if => :if condition_testing?

def condition_testing?
    !(one == 0 && two == 1)
end


推荐答案

我认为您的语法有误:

validates :one, :two, :presence => true, :if => :condition_testing?

def condition_testing?
    !(one == 0 && two == 1)
end

有一个:如果其中太多...
如果我正确理解,您只想在 one == 0&&两个== 1
然后您进行condition_testing吗?被倒置(省略!())

There was one :if too many in there... And if I understand correctly you want to have it only validate in case one == 0 && two == 1? Then you condition_testing? is inverted (leave out the !())

如果不确定,您可以尝试使用 pry 并将断点插入您的 condition_testing?方法中以查看发生了什么。

If unsure you could try to use pry and insert a breakpoint into your condition_testing? method to see what's going on.

(请注意在条件测试之前添加:)

(Please note added ":" before condition testing)

这篇关于用:if验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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