Rails 验证日期范围的唯一性 [英] Rails validate uniqueness of date ranges
问题描述
我有一个涉及员工缺勤记录的应用程序.
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, if I entered an absence record that started today and ended tomorrow, it shouldn't be possible to enter another inside of that date range in any way. So I couldn't make one that starts the day before today, then ends the day after tomorrow, or any later date.
简单地说,我需要使日期范围唯一.
To put it simply, I need to make the date range unique.
实现这一目标的最佳方法是什么?
What is the best way to achieve this?
模型类中涉及遍历所有记录的自定义验证器需要很长时间才能完成,而且我还没有找到任何解决此问题的 gem.我也没有找到任何简单的方法来通过模型中的唯一性来确定范围.我很难过:/
Custom validators in the model class that involve iterating through all records take far too long to complete, and I haven't found any gems that address this problem. I also haven't found any simply way to scope by uniqueness in the model either. I'm stumped :/
感谢您的时间!
class Absence < ActiveRecord::Base
attr_accessible :date, :date_ended, :status, :reason, :form, :user_id, :tempuser, :company_id
belongs_to :user
default_scope { where(company_id: Company.current_id) }
validates :date, :date_ended, :status, :reason, :form, :user_id, presence: true
validates_numericality_of :user_id, :only_integer => true, :message => "can only be whole number."
end
推荐答案
我使用这些:
scope :overlaps, ->(start_date, end_date) do
where "(DATEDIFF(start_date, ?) * DATEDIFF(?, end_date)) >= 0", end_date, start_date
end
def overlaps?
overlaps.exists?
end
# Others are models to be compared with your current model
# you can get these with a where for example
def overlaps
siblings.overlaps start_date, end_date
end
validate :not_overlap
def not_overlap
errors.add(:key, 'message') if overlaps?
end
# -1 is when you have a nil id, so you will get all persisted user absences
# I think -1 could be omitted, but did not work for me, as far as I remember
def siblings
user.absences.where('id != ?', id || -1)
end
来源:https://makandracards.com/makandra/984-test-if-two-date-ranges-overlap-in-ruby-or-rails
这篇关于Rails 验证日期范围的唯一性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!