【问题标题】:Validate price range overlap验证价格范围重叠
【发布时间】:2014-09-24 07:18:05
【问题描述】:

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

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

a & b #=> true

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

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

【问题讨论】:

  • 人们应该尝试回答问题而不是投反对票!

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


【解决方案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

finder 条件可能会被提取到一个作用域中。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    • 1970-01-01
    • 2016-09-18
    • 2017-05-08
    • 1970-01-01
    相关资源
    最近更新 更多