How to validate overlapping times in Rails

前端 未结 4 1311
渐次进展
渐次进展 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:35

    Take a look at this https://makandracards.com/makandra/984-test-if-two-date-ranges-overlap-in-ruby-or-rails. The key is to define one scope to chek for overlapping siblings. Somthing like this:

    # Return a scope for all interval overlapping the given interval, including the given interval itself
      named_scope :overlapping, lambda { |interval| {
        :conditions => ["id <> ? AND (DATEDIFF(start_date, ?) * DATEDIFF(?, end_date)) >= 0", interval.id, interval.end_date, interval.start_date]
      }}
    

    Also you can check this gem: https://github.com/robinbortlik/validates_overlap I think it can help.

提交回复
热议问题