简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM