How to populate fields in a has_many through join table

后端 未结 2 1522
予麋鹿
予麋鹿 2020-12-30 11:19

I have a question concerning active record association, referring to this part of the rails documentation:

http://guides.rubyonrails.org/association_basics.html#the-

相关标签:
2条回答
  • 2020-12-30 11:57

    You wish to consider nested routes, e.g.

    resources :physicians do
      resource :patients
    end
    

    The you can use things like form_for(@physician, @patient)

    and url's like physician/1/patient/23

    for updating a patient within the context of a physician.

    0 讨论(0)
  • 2020-12-30 12:04

    old question, but it should be answered - although you can assign directly to physician.patients with the << method, it creates an appointment with no values, which may or may not be valid depending on the business rules. So the more usual way to create the association would be to build the appointment on one of them

    demento = Physician.find_by_name('Dr. Demento'}
    patient = Patient.new { :name => 'Mrs. Holloway' }
    patient.appointments << Appointment.new { :physician => demento, :appointment_time => appt_time }
    

    you could combine lines 2 and 3 of course if you are so inclined.

    the line in the docs you refer to

    physician.patients = patients
    

    I think the narrow use case for that might be, if Demento had 7 patients but loses Mrs. Holloway due to an unfortunate incident with a death ray experiment, then you could do this with a updated list of the 6 extant patients and their appointments would be preserved, and Mrs. Holloway's past appointments would be automatically deleted (so as to erase any record of here, for liability insurance reasons? only Demento would be so dastardly).

    0 讨论(0)
提交回复
热议问题