Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails validations presence of either one of two fields (XOR)

How can I validate that either one of these values is present, but not both?

  validates_presence_of :client_id, message: 'Please enter a value'
  validates_presence_of :agency_id, message: 'Please enter a value'

I looked on the rails guides and I think I need to use conditional validations, but I'm still a little stuck.

like image 264
Spance Avatar asked Nov 29 '22 13:11

Spance


2 Answers

Try this

validates :client_id, presence: true, unless: :agency_id
validates :agency_id, presence: true, unless: :client_id

If you want to include the error message, you can do

validates :client_id, presence: { message: "Must have a value" }, unless: :agency_id

You can read more about validation messages

like image 105
davidhu Avatar answered Feb 20 '23 12:02

davidhu


If you use the unless syntax, you will get 2 errors: one when client_id and one when agency_id if both are Nil.

You would need a custom method if you want only one error. Guides: ActiveRecord Validation

validate :client_or_agency

def client_or_agency
  errors.add(:client_id, "Either Client or Agency needs a value") unless client_id.present? || agency_id.present?
end
like image 43
Andy Gauge Avatar answered Feb 20 '23 14:02

Andy Gauge