views:

126

answers:

2

How do I validate the presence of one field or another but not both and at least one ?

A: 

I made a cleaner way to solve this:

class Transaction < ActiveRecord::Base
    validates_presence_of :date
    validates_presence_of :name

    validates_numericality_of :charge
    validates_numericality_of :payment

    validate :charge_xor_payment

  private

    def charge_xor_payment
      if !(charge.blank? ^ payment.blank?)
        errors.add_to_base("Specify a charge or a payment, not both")
      end
    end

end

But now numericality validations does't works. Any ideas ?

benoror
+1  A: 

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, :unless => proc{|obj| obj.charge.blank?}
    validates_numericality_of :payment, :unless => proc{|obj| obj.payment.blank?}


    validate :charge_xor_payment

  private

    def charge_xor_payment
      if !(charge.blank? ^ payment.blank?)
        errors.add_to_base("Specify a charge or a payment, not both")
      end
    end

end
semanticart