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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With