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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…