每个用户轨道的日期范围重叠 [英] Date range overlap per user rails
问题描述
如何使用下面的代码验证每个用户的日期?当我以其他用户身份登录时,我无法创建具有相同日期的预订.我有 user_id 引用表用户中的 id.我希望能够使 date_start 和 date_end 仅对用户唯一,并且仍然能够为不同的用户创建相同的日期.
How can I make the validation of the date per user using the code below? When I logged in as a different user I am not able to create a reservation with the same dates. I have user_id which references id in the table users. I want to be able to make the date_start and date_end unique to only the user and still be able to create the same dates with a different user.
更多信息链接:两个日期轨道之间的验证
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
推荐答案
猜猜您可以尝试将其添加到您的验证中:
Guess you could try to add this to your validate:
validate :no_reservation_overlap, :uniqueness => { :scope => :user_id }
不确定这是否适合您,但您应该尝试一下.祝你好运!
Not sure if this works for you cause, but you should give it a try. Good luck!
我建议采用不同的方法:
I would suggest a different approach:
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
猜猜这应该可行,请试一试
Guess this should work, please give it a try
这篇关于每个用户轨道的日期范围重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!