-1

I'm working on an application where I'm entering multiple price ranges. I want to validate the price range to keep it from overlapping with another price range. I know how to check whether two arrays overlaps or not, e.g.,

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

a & b #=> true

I have two fields price_start and price_end, so no price range between these two fields should overlap with another

But here its a range, e.g. $1.0 - $10.0 then the next one $10.1 to $20, how we can implement this? please help! thanks

Rajdeep Singh
  • 17,621
  • 6
  • 53
  • 78

1 Answers1

1

You can write a custom validation like this:

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

The finder condition might be extracted into a scope.

Read more about this in the Rails guide: http://guides.rubyonrails.org/active_record_validations.html#custom-methods

spickermann
  • 100,941
  • 9
  • 101
  • 131