如何使用以下代码验证每位用户的日期?当我以其他用户身份登录时,我无法创建具有相同日期的预订。我有user_id,它在表用户中引用了id。我希望能够使date_start和date_end仅对用户唯一,并且仍然能够与不同的用户创建相同的日期。
链接了解更多信息: Validation between two date rails
validate :no_reservation_overlap
scope :overlapping, ->(period_start, period_end) do
where "((date_start <= ?) and (date_end >= ?))", period_end, period_start
end
private
def no_reservation_overlap
if (Reservation.overlapping(date_start, date_end).any?)
errors.add(:date_end, 'it overlaps another reservation')
end
end
答案 0 :(得分:2)
猜猜你可以尝试将它添加到你的验证中:
validate :no_reservation_overlap, :uniqueness => { :scope => :user_id }
不确定这是否适用于您,但您应该尝试一下。祝你好运!
编辑:
我建议采用不同的方法:
validate :no_reservation_overlap
def no_reservation_overlap
if (Reservation.where("(? BETWEEN date_start AND date_end OR ? BETWEEN date_start AND date_end) AND user_id = ?", self.date_start, self.date_end, self.user_id).any?)
errors.add(:date_end, 'it overlaps another reservation')
end
end
猜猜这应该有用,请试一试