How to populate fields in a has_many through join table

て烟熏妆下的殇ゞ 提交于 2019-11-29 09:24:16

问题


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

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

if we have three models:

class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, :through => :appointments
end

class Appointment < ActiveRecord::Base
  belongs_to :physician
  belongs_to :patient
end

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, :through => :appointments
end

The documentation says that the collection of join models can be managed via the api this way:

physician.patients = patients

but what if the appointment model, like in the linked example, has a field called appointment_date and I want to create a new appointment given the Physician and the Patient at a specific date? The following code will create a record in the appointment table, but how to populate the appointment_date too in the third step?

physician = Physician.first
patient = Patients.first
physician.patients << patient

does something like this exists?

physician.patients.create( :patient => patient, 'appointment.appointment_time' => appointment_time ) 

回答1:


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).




回答2:


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.



来源:https://stackoverflow.com/questions/7164865/how-to-populate-fields-in-a-has-many-through-join-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!