I have an application that involves absence records for employees.
I need to ensure that the start and end dates for each record don\'t overlap.
So for example,
I use these:
scope :overlaps, ->(start_date, end_date) do
where "(DATEDIFF(start_date, ?) * DATEDIFF(?, end_date)) >= 0", end_date, start_date
end
def overlaps?
overlaps.exists?
end
# Others are models to be compared with your current model
# you can get these with a where for example
def overlaps
siblings.overlaps start_date, end_date
end
validate :not_overlap
def not_overlap
errors.add(:key, 'message') if overlaps?
end
# -1 is when you have a nil id, so you will get all persisted user absences
# I think -1 could be omitted, but did not work for me, as far as I remember
def siblings
user.absences.where('id != ?', id || -1)
end
Source: https://makandracards.com/makandra/984-test-if-two-date-ranges-overlap-in-ruby-or-rails