简体   繁体   中英

How do I access attributes of the join model in a has_many :through association

Using the example on rails guides :

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

Say Appointment has the attribute exam_room_id . I want to use ActiveRecord to obtain a result set that contains a Physician's Patients and what exam room the Patient is in.

I feel like I should be able to do something like this:

Physician.first.patients.each do |patient|
  patient.appointment.exam_room_id    
end

This does not work because a Physician has_many :appointments (ie: not a single appointment).

Is there an elegant 'rails way' of accessing the attributes of Appointment together with either side of the has_many :through?

We can do the following because appointments table is included in the join query implicitly,

Physician.first.patients.select("appointments.exam_room_id ")
   .each{|patient| patient.exam_root_id}

You're going to have to step through each appointment.

Physician.first.patients.each do |patient|
  patient.appointments.each {|appointment| puts appointment.exam_room_id}
end

This would show you every exam room a patient has ever been in (based on their appointments). I don't think is exactly what you're looking for but wanted to illustrate you need to iterate over each physician or patient appointment to get the room_id.

If you're wanting a result set of current rooms you're going to want to go through the appointments. Physician.first.appointments.each . Also, how are you distinguishing between current and past appointments?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM