I have an Event model
that has form
time and to
time in my schedule app and I want to validate the overlapping time before saving.
Well, if you need a server side validation, you could implement some custom
validators in your model class:
validate :cannot_overlap_another_event
Next you need to code this method yourself:
def cannot_overlap_another_event
range = Range.new from, to
overlaps = Appointment.exclude_self(id).in_range(range)
overlap_error unless overlaps.empty?
end
Explaining what this code do, you create a Range
object with your from
and to
dates. Then it uses the helper scopes to exclude the Event
itself and check to see if there's an event in this range.
scope :in_range, -> range {
where('(from BETWEEN ? AND ?)', range.first, range.last)
}
scope :exclude_self, -> id { where.not(id: id) }
The overlap_error
is a method that populates the model's error hash to display on screen:
def overlap_error
errors.add(:overlap_error, 'There is already an event scheduled in this hour!')
end