How do I validate the presence of one field or another but not both and at least one ?
Your code will work if you add conditionals to the numericality validations like so:
class Transaction < ActiveRecord::Base validates_presence_of :date validates_presence_of :name validates_numericality_of :charge, allow_nil: true validates_numericality_of :payment, allow_nil: true validate :charge_xor_payment private def charge_xor_payment unless charge.blank? ^ payment.blank? errors.add(:base, "Specify a charge or a payment, not both") end end 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