Benamir
Benamir

Reputation: 1117

passing appointment.id to booking.appointment_id rails

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

I want to pass the appointment ID to bookings.appointment_id on create. How can I do this?

*I have edited my code in response to jordanandree suggestions. Now I am getting the following error:

NoMethodError in BookingsController#new
undefined method `bookings' for nil:NilClass 

In my home page view I have:

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

Bookings Controller:

def new
    @booking = @appointment.bookings.new 
    ...

 def create
     @booking = @appointment.bookings.new(params[:booking])
    ...

routes

resources :appointments do
    resources :bookings
 end

Your help is much appreciated.

Rake Routes:

   POST   /appointments/:appointment_id/bookings(.:format)  bookings#create 
   GET    /appointments/:appointment_id/bookings/new(.:format)  bookings#new
   GET    /appointments/:appointment_id/bookings/:id/edit(.:format) bookings#edit

Upvotes: 0

Views: 359

Answers (1)

jordanandree
jordanandree

Reputation: 553

Rails associations allows for you to create a record based on an existing record. What you have currently is a bit overkill with the parameters you have passing from the form to controller.

For example, you can change your create method to follow the same association pattern you've declared for your Booking and Appointment models:

@booking = @appointment.bookings.new(params[:booking])

This will take the id of the already-present @appointment record and set it on the new @booking instance variable.

Also, I would take a look at nested resource routing. Not sure what your routes currently look like for the two models, but it could look something like this:

resources :appointments do
  resources :bookings
end

This will provide a cleaner approach to your forms where you have new_booking_path. It would change to new_appointment_booking_path(@appointment). This would pass the ID of appointment to your booking controller where you can than create associated records for the appointment.

Upvotes: 2

Related Questions