Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate presence of one of multiple attributes in rails

Tags:

In an multilingual application, a user can input their Chinese and English names. The user can input either or both, but must input at least one name.

class Person < ActiveRecord::Base
  validates :zh_name, :presence => true
  validates :en_name, :presence => true
  validates :fr_name, :presence => true
end

Since the built-in :validates_presence_of method can only validate both attributes at once, is there a way to validate the presence of at least one of many attributes in rails?

Like a magical, validates_one_of :zh_name, :en_name, :fr_name

Thank you in advance,

like image 919
rickypai Avatar asked Mar 13 '12 07:03

rickypai


2 Answers

validate :at_least_one_name

def at_least_one_name
  if [self.zh_name, self.en_name, self.fr_name].reject(&:blank?).size == 0
    errors[:base] << ("Please choose at least one name - any language will do.")
  end
end      
like image 146
Max Williams Avatar answered Oct 12 '22 14:10

Max Williams


Taking @micapam's answer a step futher, may I suggest:

validate :has_a_name

def has_a_name
  unless [zh_name?, en_name?, fr_name?].include?(true)
    errors.add :base, 'You need at least one name in some language!'
  end
end 
like image 43
11 revs, 10 users 40% Avatar answered Oct 12 '22 13:10

11 revs, 10 users 40%