Rails validate uniqueness of date ranges

前端 未结 5 963
情深已故
情深已故 2021-02-05 23:33

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,

5条回答
  •  悲哀的现实
    2021-02-06 00:02

    While juanpastas solution is correct, it will be valid for creation of records, but can lead to false negative validations on updates.

    If you need to edit an existing record, say the range is 2014-03-13..2014-06-12 and you want to reduce it to 2014-03-13..2014-04-12, you'll get an overlap error because it is checking AGAINST itself.

      def siblings
        Absence_users.where('user_id = ? AND id != ?', user_id, self)
      end
    

    will obviate that shortcoming. (Dave T's addition should also be followed, being DB-agnostic.)

提交回复
热议问题