最多可预约15人 每家餐厅每天。 所有餐厅一天的预订不得超过 20 个。
我希望能够使用 activerecord 创建一个“条件”,其中预订日期等于参数传递的日期
def create
@reservation = Reservation.new(reservation_params)
@restaurant_date = @reservation.startreservation.strftime("%F")
pp @restaurant_date
@restaurant_reservation = Reservation.where(restaurant_id: @reservation.restaurant_id).where(:startreservation.strftime("%F") => @restaurant_date )
pp @restaurant_reservation
# if @restaurant_reservation == 15
# redirect_to restaurants_path , alert: "Reservation was not created."
# else
if @reservation.save
redirect_to reservation_url(@reservation), notice: "Reservation was successfully created."
else
render :new, status: :unprocessable_entity
end
#end
end
可能是我没把问题解释好,有什么问题我会一一解答。 :)
它是业务逻辑(检查 15 个注册),所以最好的做法是将它放在模型或服务中(而不是在控制器中),例如在模型中使用自定义验证:
class Reservation < ApplicationRecord
...
validate do |reservation|
if Reservation.where(restaurant_id: reservation.restaurant_id,
startreservation: reservation.restaurant_date).size >= 15
errors.add(:startreservation, :to_much, message: 'Too much on this date.')
end
end
...
end
...控制器:
def create
@reservation = Reservation.new(reservation_params)
if @reservation.save
redirect_to reservation_url(@reservation), notice: 'Reservation was successfully created.'
else
render :new, status: :unprocessable_entity
end
end
@restaurant_date = @reservation.startreservation.to_date
*@restaurant_reservation = Reservation.where(restaurant_id: @reservation.restaurant_id).where(startreservation: (@restaurant_date..@restaurant_date+1) ).count
if @restaurant_reservation == 15
redirect_to restaurants_path , alert: "Reservation can't be created."
else*