Rails动态范围验证

时间:2009-12-09 17:43:23

标签: ruby-on-rails validation

如何使用现有数据动态验证范围内的数字?

例如 - 我对产品的批量订购有一定的折扣。如果客户购买10-50个单位,他们将获得X关闭,如果他们订购51-200单位Y.

如何对此进行验证,以便用户无法在同一范围内进行数量折扣?

2 个答案:

答案 0 :(得分:2)

我不太明白你的问题,但我确信自定义验证将是解决你想要达到的目标的一种方法。只需在模型中添加验证方法,如下所示:

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

答案 1 :(得分:0)

如果我正确理解了您的问题,那么您正试图避免创建与现有折扣范围重叠的折扣范围。以下代码应该为您执行此操作

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 删除了一个无关的条件并添加了一些self.id检查,以确保我们没有从我们自己的记录中得到假阴性