鉴于以下模型和关联:
association model http://guides.rubyonrails.org/images/has_many_through.png
如何获得指定某一天(physician_name
)的对(patient_name
,appointment_date
)数组?您可以假设一名患者将永远不会两次去同一位医生。从不。
我已经尝试过这样的事情:
@appointments = Appointment.where(appointment_date: params[:date])
但我不知道该怎么做。我应该遍历这个数组并获得如下所示的每一对吗?
@appointments.each do |appointment|
@physician = Physicians.where(id: :appointment.physician_id)
@patient = Patients.where(id: :appointment_patient_id)
我相信有更简单的方法。
我正在使用Rails 4.2.5.1。
答案 0 :(得分:1)
我认为你想要的是这个:
Appointment.includes([:physician, :patient]).where(:date => appointment_date).map{|a| [a.physician.name, a.patient.name]}
由于只有Physician和Patient模型具有名称,因此需要在查询中加载它们(好吧,你可以通过做一些奇特的SQL技巧来避免它,但这是数据库无关的,这很方便)。因此includes
,急切加载相关模型。
然后使用.where
仅在您想要的那天返回约会(如果您实际在这些DateTime值中设置时间,则可能会更复杂。)
最后,迭代列表并返回一个包含名称的数组数组(Ruby没有元组)。