我试图写一段时间的验证,这样一段时间就不能与另一段时间重叠。此时,我的周期范围为1-52(如第1-52周)。
如果期间为20-40,我会进行验证,如果新期间位于该范围内,则会出错。
但是如果周期是33-8,那么当另一个周期重叠时,它不会引发错误。
我该怎么做?
class Period < ApplicationRecord
validate :start_week_cannot_overlap_period
validate :finish_week_cannot_overlap_period
validates :start_week, inclusion: { in: (1..52), message: '%<value>s must be a valid week number' }
validates :finish_week, inclusion: { in: (1..52), message: '%<value>s must be a valid week number' }
scope :overlapping, ->(integer) do
where 'start_week <= :integer and finish_week >= :integer', integer: integer
end
def start_week_cannot_overlap_period
return unless Period.overlapping(start_week).any?
errors.add(:start_week, 'cannot be in another Period')
end
def finish_week_cannot_overlap_period
return unless Period.overlapping(finish_week).any?
errors.add(:finish_week, 'cannot be in another Period')
end
end
答案 0 :(得分:0)
这应该有效:
scope :overlapping, ->(integer) do
where '(start_week <= :integer and finish_week >= :integer) or ' \
'(start_week > finish_week and (start_week <= :integer or finish_week >= :integer))',
integer: integer
end