0

I have a Car and Appointment model. The idea is to search for the car and create a new appointment with the car_id as a pre inputted foreign key (or association) in the appointment model.

Can I do this through the Path? I would like to add new_appointment_path(@car) on the show path for car, but this doesn't work and I'm not sure if a similar thing is possible?

There's not really any code to post, but needless to say,

Appointment 
belongs_to :car

and

Car 
has_many :appointments

Thanks

To elaborate (As I realise it's a bit unclear) I would like to be on the route 'cars/1' and click 'create appointment' to bring up the appointment form with the cars association already added.

so new_appointment_path with the car object that I'm currently on.

1 Answer 1

0

Provided you have an instance @car of the Car model, you could

link_to 'New Appointment', new_appointment_path(car_id: @car.id)

And then in the controller

class AppointmentsController < ApplicationController
  def new
    @car = params[:car_id]
    # and then the rest of the new action code
  end
end
5
  • Ok, So would this allow me to do cars/1/appointments/new to create a new form with the car association already inputted? Jan 2, 2014 at 16:30
  • That route would go toward creating a new Appointment instance for a Car instance with id = 1.
    – kddeisz
    Jan 2, 2014 at 16:32
  • Ok, the physical routes aren't necessary for me.. are they required? (I have updated my question with a brief elaboration) Jan 2, 2014 at 16:34
  • 1
    Well, that's the idea behind nested resources. If you just wanted to have it work in the way you described, you could just do new_appointment_path(car_id: @car.id), and then in your controller you could do something like def new; @car = params[:car_id]; end
    – kddeisz
    Jan 2, 2014 at 16:44
  • That's perfect! thank you. feel free to add it as an answer and I will accept. Jan 2, 2014 at 16:53

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.