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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With