Rails+postgres:在has_many through上使用Group查询



我很难理解group在Rails中是如何工作的。似乎也没有什么好的教程。。。

class Doctor
  has_many :appointments
  has_many :patients, through: :appointments
end
class Appointment
  has_many :doctors
  has_many :patients
end
class Patient
  has_many :appointments
  has_many :doctors, through: :appointments
end

Doctor类有一个字段primary_doctor。一个patient可以有多个doctors,但只能有一个primary_doctor

给定一个特定的doctor,我想要一个医生看到的所有patients的列表,按每个patientprimary_doctor分组。

doctor.patients.joins(:appointments).where(appointments: { is_primary: true }).group("patients.id, appointments.doctor_id")

这是我认为应该起作用的,但这不能进行任何分组。如果我在末尾添加一个.count,它几乎可以满足我的需求,但我得到的不是实际对象,而是{doctor_id=>patient_count}的散列。

想法?谢谢

如果我正确理解你的问题,你需要使用Ruby的内存中group_by函数。除非我在过去10年中遗漏了什么,否则ActiveRecord无法将数据库查询直接整理为您要查找的表示类型。

因此,要获得医生就诊的所有患者的列表,按每个患者的primary_doctor分组,您可以执行以下操作:

doctor.patients.joins(:appointments).where(appointments: { is_primary: true }).
  group_by(&:primary_doctor)

这会给你一个类似的结果:

{
  <Doctor id: 1, name: "Dr Bob"> =>
    [<Patient id: 1, name: "Joe">,
     <Patient id: 2, name: "Jane">],
  <Doctor id: 2, name: "Dr Spock"> =>
    [<Patient id: 3, name: "Jack">,
     <Patient id: 4, name: "Jill">,
     <Patient id: 5, name: "Scotty">]
}

注意,如果你每次都必须返回数据库才能获得primary_doctor,这可能会有点低效,所以如果这是你应用程序中的关键路径,你可能也会使用includes(http://apidock.com/rails/ActiveRecord/QueryMethods/includes)在那里的某个地方。

最新更新