Search code examples
ruby-on-railsrubyactiverecord

Activerecord::Datetime>objects


a maximum of 15 reservations can be made per day per restaurant. No more than 20 reservations should be allowed for a single day across all restaurants.

I want to be able to make a "condition" with activerecord where the reservation date is equal to the date that is passed by the parameter

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

It may be that I did not explain the problem well, any questions I will answer at the moment. :)


Solution

  • It is business logic (checking for 15 registrations), so the best practice is place it in model or service (not in controller), for example use custom validation in model:

    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
    

    ... controller:

    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 Validations