How to validate overlapping times in Rails

前端 未结 4 1346
渐次进展
渐次进展 2021-01-20 07:08

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.

4条回答
  •  不要未来只要你来
    2021-01-20 07:22

    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
    

提交回复
热议问题