ruby Activerecord::Datetime>objects

qkf9rpyu  于 2023-05-17  发布在  Ruby
关注(0)|答案(2)|浏览(206)

每间餐厅每天最多可预订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

可能是我没有很好地解释问题,任何问题我都会在此刻回答。:)

h5qlskok

h5qlskok1#

它是业务逻辑(检查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

ActiveRecord验证

niknxzdl

niknxzdl2#

@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*

相关问题