两个日期栏之间的验证 [英] Validation between two date rails
问题描述
我正在尝试创建预订/预订约会,用户选择两个日期开始日期和结束日期,如何验证开始日期和结束日期之间的日期以及验证这两个日期之间的日期防止用户再次选择开始日期、结束日期以及两者之间的日期.
I am trying to create a reservation/booking appointment, the user select two dates the starting date and the end date, how can I validate the date from the starting and the end date and also validate the dates in between those two dates preventing the user from choosing again the starting, end date and the dates in between.
数据库
date_start | date_end
14/11/2017 14/18/2017
查看:
日期字段
<%= f.label :'date_start:' %>
<%= f.date_field :date_start %>
<%= f.label :'date_end:' %>
<%= f.date_field :date_end %>
型号
class Reservation < ApplicationRecord
belongs_to: user
validates :date_start, uniqueness: true
validates :date_end, uniqueness: true
end
我使用了 validates :date_start, uniqueness: true
和 validates :date_end, uniqueness: true
但它只检查日期开始和 date_end 但它不检查它们之间的日期.
I used validates :date_start, uniqueness: true
and validates :date_end, uniqueness: true
but it only checks for the date start and the date_end but it does not check the dates in between them.
推荐答案
您将必须有一个单独的方法来保存复杂的验证代码.使用 validate :method_name
(不带 's')来调用它.
You're going to have to have a separate method to hold the complex validation code. Use validate :method_name
(without an 's') to call it.
如果发现问题,该方法应该向对象添加错误.
The method should add error(s) to the object if it finds a problem.
像这样:
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
这篇关于两个日期栏之间的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!