我的模型上的reservation_start
和reservation_end
属性上有一些自定义验证
class DateRangeValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.date_ranges.each do |range|
if range.include? value
record.errors.add(attribute, "#{options[:name]} not available")
end
end
end
end
预订模式:
class Reservation < ActiveRecord::Base
belongs_to :user
belongs_to :transport
validates_presence_of :user, :transport, :reservation_start, :reservation_end
validates :reservation_start,
date_range: {name: "Start date"},
date_past: true
validates :reservation_end,
date_range: {name: "End date"},
date_subset: true,
start_bigger: true
def date_ranges
reservations = Reservation.where(["transport_id =?", transport_id])
reservations.map { |e| e.reservation_start..e.reservation_end }
end
end
问题在于,例如,如果我想编辑一条记录,将reservation_end
减少一天验证就会启动。我尝试将验证设置为on: :create
,但这不是一个好主意。
最好的方法是什么?
答案 0 :(得分:1)
我最初的想法是在date_ranges
中更改您的查询以排除当前记录,如果它已经被保留(即已填充id
字段)。它看起来像是:
def date_ranges
reservations = Reservation.where({transport_id: transport_id})
reservations = reservations.where(['id <> ?', id]) if !id.nil?
reservations.map { |e| e.reservation_start..e.reservation_end }
end
行reservations = reservations.where(['id <> ?', id]) if !id.nil?
应该排除当前记录iff(当且仅当它)已被保留,在这种情况下,验证应该在编辑以前创建的Reservation
时通过,只要它不与任何其他Reservation
重叠。