使用上rails guides的例子:如何访问的连接模型的属性在的has_many:通过关联
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
说Appointment
具有属性exam_room_id
。我想使用ActiveRecord来获得含Physician's
Patients
什么考场的Patient
是在结果集中
我觉得我应该可以做这样的事情:
Physician.first.patients.each do |patient|
patient.appointment.exam_room_id
end
这确实不工作,因为Physician has_many :appointments
(即:不是一个约会)。
有一种优雅的“轨道的方式”获取的Appointment
属性与的has_many :through?
你需要的结果集返回exam_room_id为所有的约会? – rb512
我认为你实际上不得不要求''patient.appointment.first.exam_room_id'' –
rrb:理想情况下,结果集对于“Physician”,“Appointment”和“Patient”的每个组合都有一条记录 - 就好像查询是针对预约表所写的一样,并且还抓取了医生和患者的数据。我意识到我可以使用自定义sql甚至ActiveRecord表来解决问题 - 我希望这样做有一个很好的“rails方式”。 – rswolff