I'm struggling with understanding how group works in Rails. There doesn't really appear to be any good tutorials either...
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
The Doctor class has a field primary_doctor. A patient can have many doctors, but only one primary_doctor.
Given a specific doctor, I want a list of all patients that doctor sees, grouped by the primary_doctor for each patient.
doctor.patients.joins(:appointments).where(appointments: { is_primary: true }).group("patients.id, appointments.doctor_id")
is what I feel should work, but that doesn't do any grouping. If I add a .count to the end, it almost gives me what I want, but instead of the actual objects, I get a hash of {doctor_id=>patient_count}.
Thoughts? Thanks!
selectthe fields you need after grouping.