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