Validate presence of one field or another (XOR)

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
    return if charge.blank? ^ payment.blank?

    errors.add(:base, 'Specify a charge or a payment, not both')
  end
end

Leave a Comment