Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate fields in a has_many through join table

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 ) 
like image 572
Gnagno Avatar asked Aug 23 '11 17:08

Gnagno


2 Answers

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

like image 164
sbeam Avatar answered Nov 15 '22 10:11

sbeam


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.

like image 21
Michael Durrant Avatar answered Nov 15 '22 08:11

Michael Durrant