使用 :if 进行验证
我试图创建一个条件,其中属性“一”为零且属性“二”为一,则模型无效。但是当我做:
Model.create(:one => 1, :two => 0).valid?
单元测试返回true
!为什么?
validates :one, :two, :presence => true, :if => :if condition_testing?
def condition_testing?
!(one == 0 && two == 1)
end
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?
The unit test returns true
! Why?
validates :one, :two, :presence => true, :if => :if condition_testing?
def condition_testing?
!(one == 0 && two == 1)
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以用一行验证它:
You can validate it in one line:
你最好使用数字和等于。
http://guides.rubyonrails.org/active_record_validations_callbacks.html#numericality
You are better off using numericality and equal to.
http://guides.rubyonrails.org/active_record_validations_callbacks.html#numericality
问题在于您正在使用带有检查属性值的条件的存在验证器。这是不正确的。存在验证器检查以确保设置了这些属性。更糟糕的是,您传递了
if
选项(顺便说一句,@Tigraine 对于您的语法错误是正确的),这意味着每当该方法返回 true 时,根本不会检查是否存在。按照您的设置方式,只有当one
等于 1 并且two
等于 0 时,验证器才会运行。否则,根本不会运行任何验证!我认为这里最好的选择是编写自定义验证:如果条件返回 true,这将使用指定的消息向模型添加错误。 (注意:我仍然不清楚哪些条件有效,哪些条件无效,因此请随意更改最后一部分以满足您的需求。)
The problem is that you're using a presence validator with a condition that checks the values of the attributes. This is incorrect. A presence validator checks to make sure those attributes are set. What's worse, you're passing the
if
option (@Tigraine was correct about your syntax being wrong, by the way), which means whenever that method returns true, the presence won't be checked at all. The way you have this set up, the validator will run only whenone
is equal to 1 andtwo
is equal to 0. Otherwise, no validations are run at all! I think the best option here is to write a custom validation:This will add an error to the model with the specified message if the condition returns true. (Note: I'm still not clear on what condition is valid and which is invalid, so feel free to change that last part to suit your needs.)
我认为你的语法有错误:
有一个:如果那里太多......
如果我理解正确的话,你只想让它在
one == 0 && 的情况下验证。两个 == 1 ?
然后你进行条件测试?是反转的(省略 !())
如果不确定,您可以尝试使用 pry 并将断点插入到您的
condition_testing?
方法来查看发生了什么。(请注意条件测试前添加“:”)
I think you have an error in your syntax:
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 !())
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)