rails存在2个字段之间的条件验证

时间:2021-02-20 11:49:39

first rails program here. I would like to go a little further than req'd and, for instance, allow entries into an address book accept a first name OR a last name or both. In other words, I would like to validate_presence_of first OR last, and only throw an exception if both are missing, a super easy thing to do in C++, but what would syntax look like in Ruby?

第一个铁路计划在这里我想比req'd更进一步,例如,允许在地址簿中输入接受名字或姓氏或两者。换句话说,我想首先或者最后验证validate_presence_of,并且如果两者都丢失则只抛出异常,这在C ++中是一件非常容易的事情,但是Ruby中的语法会是什么样子?

2 个解决方案

#1


12  

Couldn't you just run a conditional validates presence of last_name if first_name is blank? If the first name is NOT blank, then the validation won't run, but if it is blank then it makes sure the last_name is not also blank...

如果first_name为空,您是否只能运行条件验证last_name的存在?如果第一个名称不是空白,则验证将不会运行,但如果它是空白则确保last_name不是空白...

validates :last_name, :presence => true, :if => "first_name.blank?"

#2


1  

You want a custom validation method as described here.

您需要一个如此处所述的自定义验证方法。

#1


12  

Couldn't you just run a conditional validates presence of last_name if first_name is blank? If the first name is NOT blank, then the validation won't run, but if it is blank then it makes sure the last_name is not also blank...

如果first_name为空,您是否只能运行条件验证last_name的存在?如果第一个名称不是空白,则验证将不会运行,但如果它是空白则确保last_name不是空白...

validates :last_name, :presence => true, :if => "first_name.blank?"

#2


1  

You want a custom validation method as described here.

您需要一个如此处所述的自定义验证方法。