Benamir
Benamir

Reputation: 1117

ActiveRecord::RecordNotFound in BookingsController#create Couldn't find Appointment without an ID

app/controllers/bookings_controller.rb:45:in `create'

I have an Appointments object and a Bookings object. Bookings belongs to Appointments and Appointments has_many bookings.

I want to create a bookings object that has :appointment_id

Here is my code:

<% @appointments.each do |appointment| %>
    <%= link_to "new Booking", new_appointment_booking_path(appointment)%>
<%end%>

Bookings Controller:

def new
    @appointment = Appointment.find(params[:appointment_id])
    @booking = @appointment.bookings.new 
    ...

 def create
I was missing [:booking] in line 45. 
 Line 45:   @appointment = Appointment.find(params[:booking][:appointment_id])
     @booking = @appointment.bookings.new(params[:booking])

routes

resources :appointments do
    resources :bookings
end

When I submit my Bookings_form the correct appointment_id is passed through but I get the following error:

ActiveRecord::RecordNotFound in BookingsController#create
Couldn't find Appointment without an ID

Booking _form

<%= simple_form_for(@booking) do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <%= f.input :appointment_date %>
    <%= f.input :start_time %>
    <%= f.input :end_time %>
    <%= f.input :name %>
    <%= f.input :phone_number %>
    <%= f.hidden_field :appointment_id%>  

 <div class="form-actions">
     <%= f.button :submit %>
  </div>

Upvotes: 0

Views: 507

Answers (1)

David Underwood
David Underwood

Reputation: 4966

You're not passing the Appointment id back to the create method.

The create method knows nothing except the info passed in through the params hash from the form inputs. Seeing as you haven't added a field to the form for appointment_id, it's not getting passed to the controller and isn't available in the create method.

To get around this, add a new hidden input to your form like this:

<%= f.input :appointment_id, :type => :hidden %>

Now you're explicitly passing the id through the form post, so it'll be available in your controller.

Upvotes: 1

Related Questions