views:

104

answers:

2

How can I validate a number within a range dynamically using existing data?

For example - I have certain discounts on bulk ordering of products. If a customer buys 10-50 units they get X off and if they order 51-200 units Y off.

How can I validate this so that users can't put in quantity discounts over the same range?

+1  A: 

I don't quite understand your question but I'm sure a custom validation would be one way to solve whatever you are trying to achieve. Simply add a validate method in your model like so:

def validate
    self.errors.add(:amount, "is out of range") unless self.amount_in_allowed_range
end

private
    def amount_in_allowed_range
      # logic to return true or false
    end
tsdbrown
A: 

If I understand your question correctly then you are trying to avoid the creation of a discount range that overlaps an already existing one. The following code should do this for you

class QtyDiscount < ActiveRecord::Base

def validate
    self.errors.add(:amount, "overlaps an existing range") 
       unless self.amount_in_allowed_range
end

    def amount_in_allowed_range
      # Check for overlapping ranges where our record either
      # - overlaps the start of another 
      # - or overlaps the end of another
      conditions = "
        id != :id AND (
        ( min_value BETWEEN :min_value AND :max_value) OR
        ( max_value BETWEEN :min_value AND :max_value))"

      puts "Conditions #{conditions}"
      overlaps = QtyDiscount.find(:all, :conditions => 
        [ conditions, { :id => self.id.nil? ? 0 : self.id, 
                        :min_value => self.min_value, 
                        :max_value => self.max_value} ])
      overlaps.size == 0
    end

end

EDITED Removed an extraneous condition and added some checking for self.id to ensure we are not getting a false negative from our own record

Steve Weet