预订应用程序.如何检查或验证日期,例如date_start和date_end的值为
date_start date_end 26-11-2017 27-11-2017
我将创建另一个具有这些起始和结束日期值的保留,但它与其他值冲突.如何查看有冲突的日期?
date_start date_end 25-11-2017 28-11-2017
用它来验证两者之间的日期
模型
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
查看 – 选择日期
<%= f.label :'date_start:' %> <%= f.date_field :date_start %> <%= f.label :'date_end:' %> <%= f.date_field :date_end %>
样本日期26到27已经预订/保留,据说它必须防止插入25到28,因为已经预订了26到27.
解决方法
模型:
class Reservation < ApplicationRecord validate :overlapping private def overlapping if Reservation.where('? < date_end and ? > date_start',self.date_start,self.date_end).any? errors.add(:date_end,'it overlaps another') end end
架构:
create_table "reservations",force: :cascade do |t| t.date "date_start" t.date "date_end" t.datetime "created_at",null: false t.datetime "updated_at",null: false end
这是我尝试创建(24 nov – 27 nov)和(25 nov – 27 nov)时有轨道控制台日志(25 nov – 26 nov)
irb(main):003:0> Reservation.create date_start: Date.parse('25-11-2017'),date_end: Date.parse('26-11-2017') (0.2ms) BEGIN (0.6ms) SELECT COUNT(*) FROM "reservations" WHERE ('2017-11-25' date_start) sql (0.6ms) INSERT INTO "reservations" ("date_start","date_end","created_at","updated_at") VALUES ($1,$2,$3,$4) RETURNING "id" [["date_start","2017-11-25"],["date_end","2017-11-26"],["created_at","2017-11-21 13:23:05.192276"],["updated_at","2017-11-21 13:23:05.192276"]] (10.7ms) COMMIT => # irb(main):004:0> Reservation.create date_start: Date.parse('24-11-2017'),date_end: Date.parse('27-11-2017') (0.1ms) BEGIN (0.2ms) SELECT COUNT(*) FROM "reservations" WHERE ('2017-11-24' date_start) (0.2ms) ROLLBACK => # irb(main):005:0> Reservation.create date_start: Date.parse('25-11-2017'),date_end: Date.parse('26-11-2017') (0.1ms) BEGIN (0.3ms) SELECT COUNT(*) FROM "reservations" WHERE ('2017-11-25' date_start) (0.1ms) ROLLBACK => #
有预期的回滚.