3

Given the following models, how can I eager load a doctors specialty so I don't get crushed in a loop? Right now I'm able to load the Doctor and User user models but I'd also like to be able to load their profiles and, if possible, the doctors specialty.

MedicalRelationship.includes(:doctor, :user).where(user_id: [1,2,3])


class MedicalRelationship < ActiveRecord::Base
  belongs_to :user
  belongs_to :doctor, :class_name => "User"
end

class DoctorProfile < ActiveRecord::Base
  has_one :user, as: :profile, dependent: :destroy
  belongs_to :specialty
end

class PatientProfile < ActiveRecord::Base
  has_one :user, as: :profile, dependent: :destroy
end

class Specialty < ActiveRecord::Base
  has_many :doctors, class_name: "DoctorProfile"
end
user2954587
  • 4,661
  • 6
  • 43
  • 101

2 Answers2

3

You should be able to load them as follows

MedicalRelationship.includes({ doctor: { DoctorProfile: :specialty } }, :user).where(user_id: [1,2,3])

as shown in this answer by Joe Kennedy.

Community
  • 1
  • 1
Roope Hakulinen
  • 7,326
  • 4
  • 43
  • 66
  • This would fail if someone have a namespaced class for models. `{ DoctorProfile: :specialty }` would not work. You have to use: `{ doctor_profile: :specialty }` – K M Rakibul Islam Aug 22 '15 at 21:34
1

Active Record lets you eager load any number of associations with a single Model.where/Model.find call by using an array, hash, or a nested hash of array/hash with the includes method.

In your case, you can eager load your all the associated models of MedicalRelationship using this:

MedicalRelationship.includes({ doctor: { doctor_profile: :specialty } }, :user).where(user_id: [1,2,3])

I strongly recommend you to read the Eager Loading Multiple Associations official documentation which explains it with some clear examples.

K M Rakibul Islam
  • 33,760
  • 12
  • 89
  • 110