问题描述
我有一个包含手机/手机号码和家庭电话号码的表格.
I have a form with a mobile/cell number and a home phone number.
如果电话号码留空,我只想验证手机/手机号码是否存在,反之亦然.
I want to have only validate presence of mobile/cell number if the phone number has been left blank or vice versa.
我目前对这些字段的验证如下.
My current validations for these fields are as follows.
validates_presence_of :mobile_number
validates_presence_of :home_phone
validates_length_of :home_phone, :minimum => 12, :maximum => 12
validates_length_of :mobile_number, :minimum => 10, :maximum => 10, :allow_blank => true
validates_format_of :home_phone, :with => /\A[0-9]{2}\s[0-9]{4}\s[0-9]{4}/, :message => "format should be 02 9999 9999"
我想我可以有类似以下的东西,但不知道如何准确地做到这一点.
I thought I could have something like the following but not sure how to do this exactly.
validates_presence_of :mobile_number, :unless => :home_phone.blank?
我使用的是 Rails 3.
I'm using Rails 3.
推荐答案
您不需要 lambda.这样做:
You don't need a lambda. This will do:
validates_presence_of :mobile_number, :unless => :home_phone?
此外,所有验证器都采用相同的 if/unless 选项,因此您可以随意使它们成为条件.
Also, all of the validators take the same if/unless options, so you can make them conditional at will.
更新:几天后回顾这个答案,我发现我应该解释它为什么有效:
Update: Looking back at this answer a few days later, I see that I should explain why it works:
- 如果您将验证器的
:unless
选项设置为符号,Rails 将查找该名称的实例方法,在正在验证的实例上调用该方法 -- 在验证时 --并且只有在方法返回 false 时才执行验证. - ActiveRecord 会自动为模型的每个属性创建问号方法,因此模型表中
home_phone
列的存在会导致 Rails 创建一个方便的#home_phone?
方法.当且仅当 home_phone 存在(即不为空)时,此方法才返回 true.如果 home_phone 属性为 nil 或空字符串或一堆空格,home_phone?将返回 false.
- If you set a validator's
:unless
option to be a symbol, Rails will look for an instance method of that name, invoke that method on the instance that's being validated -- at validation time -- and only perform the validation if the method returns false. - ActiveRecord automatically creates question mark methods for each of your model's attributes, so the existence of a
home_phone
column in your model's table causes Rails to create a handy#home_phone?
method. This method returns true if and only if home_phone is present (i.e. not blank). If the home_phone attribute is nil or an empty string or a bunch of white space, home_phone? will return false.
更新:确认这种旧技术在 Rails 5 中继续有效.
UPDATE: Confirmed that this old technique continues to work in Rails 5.
这篇关于仅当另一个字段为空时验证字段的存在 - Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!