1

在我的一项验证中,我想确保用户日期范围输入不与现有存储的日期范围重叠:

class Timecard < ActiveRecord::Base
  validate :does_not_intersect_with_existing_timecards

  def does_not_intersect_with_existing_timecards
    if from_date && to_date &&
      !Timecard.where("? <= to_date AND ? >= from_date", from_date, to_date).empty?
      errors.add(:from_date, "must not intersect with existing timecards")
    end
  end
end

问题是如果从方法调用此验证将失败update(因为该where子句将在数据库中找到当前正在更新的记录)。我不想只 validate on: :create,因为用户可以编辑日期范围。

如何从验证查询中排除当前模型?

我似乎无法访问id@id从验证方法中访问...

4

2 回答 2

2

试试这个

def does_not_intersect_with_existing_timecards
  if self.new_record?  
     errors.add(:from_date, "must not intersect with existing timecards") if from_date && to_date && !Timecard.where("? <= to_date AND ? >= from_date ", from_date, to_date).empty?
  else
     errors.add(:from_date, "must not intersect with existing timecards") if from_date && to_date && !Timecard.where("? <= to_date AND ? >= from_date AND id != ?", from_date, to_date, self.id).empty?
  end

end

或者

def does_not_intersect_with_existing_timecards
   errors.add(:from_date, "must not intersect with existing timecards") if from_date && to_date && !Timecard.where("#{self.new_record? || 'id != ' + self.id.to_s} AND ? <= to_date AND ? >= from_date ", from_date, to_date).empty?
end
于 2013-09-27T11:07:23.047 回答
1

您可以使用before_save钩子代替validation

于 2013-09-27T11:03:50.373 回答