所以我目前正在从事汽车预订功能
用户当前可以通过选择汽车的开始时间和结束时间来预订汽车
预订模式如下:
create_table "bookings", force: :cascade do |t|
t.integer "user_id"
t.integer "car_id"
t.datetime "start_time"
t.datetime "end_time"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["car_id"], name: "index_bookings_on_car_id"
t.index ["user_id"], name: "index_bookings_on_user_id"
end
这是汽车的架构:
create_table "cars", force: :cascade do |t|
t.string "name"
t.string "make"
t.string "model"
t.string "number_plate"
t.string "color"
t.string "seat_count"
t.string "current_address"
t.string "latitude"
t.string "longitude"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "status", default: "Available"
end
完成预订后,汽车的状态将从“可用”变为“不可用”,目前这是在我的预订控制器创建方法中完成的:
def create
params[:booking][:user_id]= current_user.id
@booking = Booking.new(booking_params)
respond_to do |format|
if @booking.save
@booking.car.update(status: "Unavailable")
format.html { redirect_to @booking, notice: 'Booking was
successfully created.' }
format.json { render :show, status: :created, location: @booking }
else
format.html { render :new }
format.json { render json: @booking.errors, status:
:unprocessable_entity }
end
end
end
这是我目前的预订模型:
class Booking < ApplicationRecord
validate :bookings_must_not_overlap
belongs_to :user
belongs_to :car
private
def bookings_must_not_overlap
return if self
.class
.where.not(id: id)
.where(car_id: car_id)
.where('start_time < ? AND end_time > ?', end_time,
start_time)
.none?
errors.add(:base, 'The car has already been booked for that time frame')
end
结束
我目前遇到的问题是,在预定的end_time过后,状态又变回了“ Available”。
在此方面的任何帮助将不胜感激
答案 0 :(得分:2)
您可以使用jobs。
class ResetCarAvailabilityJob < ApplicationJob
queue_as :default
def perform(car)
car.update(status: "Available")
end
end
并在预订汽车后延迟执行此工作:
ResetCarAvailabilityJob.set(wait_until: @booking.end_time).perform_later(@booking.car)