Rails validate uniqueness of date ranges

前端 未结 5 969
情深已故
情深已故 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条回答
  •  旧时难觅i
    2021-02-05 23:54

    Use the gem validates_overlap.

    gem 'validates_overlap'
    

    For example, if you have a model called Meeting with a start_date and end_date fields of type date, you can easily validate that they don't overlap.

    class Meeting < ActiveRecord::Base
      validates :start_date, :end_date, overlap: true 
    end
    

    Another more realistic example, say a Meeting belongs_to a User, you can scope it out, so it only validates meetings for a particular user.

    class Meeting < ActiveRecord::Base
      belongs_to User
      validates :start_date, :end_date, overlap: { scope: 'user_id',
                                                 message_content: 'overlaps with Users other meetings.' }
    end
    

提交回复
热议问题