gpt4 book ai didi

ruby-on-rails - Rails 验证日期范围的唯一性

转载 作者:行者123 更新时间:2023-12-04 01:21:35 25 4
gpt4 key购买 nike

我有一个涉及员工缺勤记录的应用程序。

我需要确保每条记录的开始日期和结束日期不重叠。

因此,例如,如果我输入了从今天开始到明天结束的缺勤记录,则不应以任何方式输入该日期范围内的另一个记录。所以我不能让一个从今天开始,然后在后天或任何更晚的日期结束。

简单地说,我需要使日期范围唯一。

实现这一目标的最佳方法是什么?

模型类中涉及遍历所有记录的自定义验证器需要很长时间才能完成,而且我还没有找到任何解决这个问题的 gem。我也没有找到任何简单的方法来通过模型中的唯一性来确定范围。我很难过:/

谢谢你的时间!

编辑:

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

关于ruby-on-rails - Rails 验证日期范围的唯一性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16252423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com