验证价格范围重叠

时间:2014-09-24 07:18:05

标签: ruby-on-rails ruby ruby-on-rails-3 validation rails-models

我正在处理我输入多个价格范围的应用程序。我想验证价格范围,以防止与其他价格范围重叠。我知道如何检查两个数组是否重叠,例如,

a = [1.0, 2.0]
b = [2.0, 3.0]

a & b #=> true

我有两个字段price_start和price_end,因此这两个字段之间的价格范围不应与另一个字段重叠

但这是一个范围,例如$ 1.0 - $ 10.0然后下一个$ 10.1到$ 20,我们如何实现这个?请帮忙!感谢

1 个答案:

答案 0 :(得分:1)

您可以编写如下自定义验证:

validates :price_range_must_not_overlap

private
def price_ranges_must_overlap
  range = (price_start..price_end)
  if self.class.
          where('id <> ?', self.id)
          where('(price_start BETWEEN :price_start AND :price_end) OR (price_end BETWEEN :price_start AND :price_end)',
                { :price_start => price_start,
                  :price_end   => price_end }).any?
    errors.add(:base, "Price range overlaps with an existing price range")(b)
  end
end

可以将取景器条件提取到范围中。

在Rails指南中了解更多相关信息:http://guides.rubyonrails.org/active_record_validations.html#custom-methods