日期范围验证不允许更新

时间:2014-12-08 15:36:22

标签: ruby-on-rails ruby

我的模型上的reservation_startreservation_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,但这不是一个好主意。

最好的方法是什么?

1 个答案:

答案 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重叠。