Richbits
Richbits

Reputation: 7624

Rails Many to Many with common children

Within my sample application, I have

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

Database model

Across a week, I a doctor has appointments to see 20 patients including one patient twice. For doc = Physician.first, if I look at the patients list doc.patients I get a list of patients, one for each appointment, including one patient listed twice. I just want a list of unique patients. I know that doc.patients.uniq will get me a list of unique patients, but I do not understand why this isn't what is returned in the first place.

I'd be grateful for any explanation of why this works this way and whether actually my model should be structured differently.

Upvotes: 0

Views: 41

Answers (1)

SataGNUk
SataGNUk

Reputation: 96

In your model you can do

has_many :patients, -> { uniq }, through: :appointments

The uniq scope needs to passed as the second argument to has_many. (Thanks to coorasse for the updated syntax.)

You are getting duplicates because rails picks up all the patient associations made through appointments, so if a patient has more than one appointment, that's more than one record, and rails will pick up all records. Adding :uniq tells SQL to get unique records.

Upvotes: 2

Related Questions