Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Active Record eager load across models

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
like image 667
user2954587 Avatar asked Jun 05 '26 15:06

user2954587


2 Answers

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.

like image 200
Roope Hakulinen Avatar answered Jun 07 '26 09:06

Roope Hakulinen


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.

like image 31
K M Rakibul Islam Avatar answered Jun 07 '26 08:06

K M Rakibul Islam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!