避免小巴预订系统的双重预订 [英] Avoid double bookings for a minibus reservation system

查看:55
本文介绍了避免小巴预订系统的双重预订的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试建立一个预订系统,客户可以在其中预订小巴.我已经能够获得所有数据,因此可以进行预订.

I'm trying to build a reservation system where a customer can reserve a minibus. I've been able to get the all the data so a booking can be made.

我试图避免其他用户在同一天预订小巴.我不确定如何像在 ruby​​ on rails 中那样做.

I'm trying to avoid another user to reserve the minibus for the same day. I'm not to sure how to go about it as in new to ruby on rails.

在我的reservation.rb我有

In my reservation.rb I've got

 belongs_to :vehicle
 belongs_to :user

在我的 user.rb 和 Vehicle.rb 中,我有

In my user.rb and vehicle.rb I've got

has_many :reservation

在我的预订控制器中,我有

In my reservation controller I've got

 def new
    @vehicle = Vehicle.find(params[:vehicle_id])
    @reservation = Reservation.new(user_id: User.find(session[:user_id]).id)
    @reservation.vehicle_id = @vehicle.id
  end

我会使用验证来阻止双重预订吗?会不会像我的reservation.rb

would I use validation to stop double reservations? would it be something like in my reservation.rb

validates :vehicle_id, :startDate, :uniqueness => { :message => " minibus already reserved"}

虽然以上只允许预约车辆.

Although the above will only allow the vehicle to be reserved.

任何帮助将不胜感激!

推荐答案

正如您已经发现的,您不能使用 Rails 的内置唯一性验证器来验证两个范围不重叠.

As you already figured out you cannot use Rails' built-in uniqueness validator to validate that two ranges do not overlap.

您必须构建一个自定义验证来检查这一点.检查两个时间或日期范围 AB 是否重叠的条件非常简单.看看这张图片.

You will have to build a custom validation to check this. A condition that checks if two time or date ranges A and B overlap is quite simple. Have a look at this image.

A:      |-----|
B1:   |-----|
B2:   |---------|
B3:       |-----|
C1: |-|
C2:             |-|

AB 重叠如果 B.start <;A.结束&&B.结束 >A.开始

将以下内容添加到您的模型中:

Add the following to your model:

# app/models/reservation.rb
validate :reservations_must_not_overlap

private

def reservations_must_not_overlap
  return if self
              .class
              .where.not(id: id)
              .where(vehicle_id: vehicle_id)
              .where('start_date < ? AND end_date > ?', end_date, start_date)
              .none?

  errors.add(:base, 'Overlapping reservation exists')
end

一些注意事项:

  • 您可能需要调整数据库列的命名和属性名称,因为我不确定这是否只是拼写错误,或者您使用的名称是否不遵循 Ruby 约定.
  • 此外,您可能需要 <=>=(而不是 <>>),取决于您对开始和结束的定义.
  • 将条件移动到命名范围内是个好主意,可以提高可读性
  • You might need to adjust the naming of the database columns and the attributes names because I wasn't sure if it was just a typo or if you use names not following Ruby conventions.
  • Furthermore, you might need <= and >= (instead of < and >), depending on your definition of start and end.
  • Moving the condition into a named scope is a good idea and will improve readability

这篇关于避免小巴预订系统的双重预订的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆