Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails presence conditional validation between 2 fields

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?

like image 352
blinking-in-the-light Avatar asked Oct 07 '13 05:10

blinking-in-the-light


2 Answers

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...

validates :last_name, :presence => true, :if => "first_name.blank?"
like image 112
Helios de Guerra Avatar answered Oct 02 '22 07:10

Helios de Guerra


You want a custom validation method as described here.

like image 24
Vidya Avatar answered Oct 02 '22 08:10

Vidya