1

Rails 4, Ruby 2.3.1 (noob alert)

I have a restaurant reservation app. before a reservation is saved I need to check the db to ensure there is a table available. To do this I check the date and time selected in the form with a count:

Reservation.where(r_date:params[:r_date],r_time:params[:r_time]).count < 3

assuming the restaurant has 3 tables. If the count is more than 3 then there is not a table available.

How do I get the params from @reservation in the controller to the callback function in the model?

1
  • Where is @reservation var in your controller and what is "callback function in the model"? It is not quite clear what you mean. Commented Jun 23, 2016 at 4:34

1 Answer 1

1

You can use a before_save method to check availability, and invalidate the model, canceling the save, if there are no tables available.

In your controller:

class ReservationsController < ApplicationController
  def create
    @reservation = Reservation.new(reservation_params)
    if @reservation.save
      redirect_to reservation_path(@reservation)
    else
      render 'new'
    end
  end

  private

  def reservation_params
    params[:reservation].permit(:r_date, :r_time)
  end
end

Then, in your model:

class Reservation < ActiveRecord::Model
  before_save :check_availability

  private

  def check_availability
    reservation_count = Reservation.where(r_date: self.r_date, r_time: self.r_time).count
    if reservation_count > 3
      return false
    end
  end
end

I haven't had a chance to test this code, so please let me know if you have any problems.

Edit: explanation

Sign up to request clarification or add additional context in comments.

2 Comments

thank you ajpocus! How do I add a flash or error to this callback?
No problem @phillipjones1! You should be able to set flash[:notice] = "your message here" before the render 'new' call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.