How to implement has_many :through relationships with Mongoid and mongodb?-open source projects mongoid/mongoid

franciscodelgadodev

Steven Soroka solution is really great! I don’t have the reputation to comment an answer(That’s why I’m adding a new answer :P) but I think using map for a relationship is expensive(specially if your has_many relationship have hunders|thousands of records) because it gets the data from database, build each record, generates the original array and then iterates over the original array to build a new one with the values from the given block.

Using pluck is faster and maybe the fastest option.

class Physician
  include Mongoid::Document
  has_many :appointments

  def patients
    Patient.in(id: appointments.pluck(:patient_id))
  end
end

class Appointment
  include Mongoid::Document
  belongs_to :physician
  belongs_to :patient 
end

class Patient
  include Mongoid::Document
  has_many :appointments 

  def physicians
    Physician.in(id: appointments.pluck(:physician_id))
  end
end

Here some stats with Benchmark.measure:

> Benchmark.measure { physician.appointments.map(&:patient_id) }
 => # 

> Benchmark.measure { physician.appointments.pluck(:patient_id) }
 => # 

I am using just 250 appointments. Don’t forget to add indexes to :patient_id and :physician_id in Appointment document!

I hope it helps, Thanks for reading!