Active Record对模型的热切加载

时间:2015-08-22 15:35:35

标签: ruby-on-rails activerecord

鉴于以下型号,我如何急切地加载医生专业,这样我就不会被碾压?现在我可以加载DoctorUser用户模型,但我也希望能够加载他们的profiles,如果可能的话,还可以加载医生专业。

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

2 个答案:

答案 0 :(得分:3)

您应该可以按如下方式加载它们

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

in this answer所示Joe Kennedy

答案 1 :(得分:1)

通过使用static string[] Scopes = { GmailService.Scope.GmailReadonly }; eager loadModel.where/Model.find {{},{®> Active Record可让arrayhash次呼叫的任意数量的关联1}}使用nested hash方法。

在您的情况下,您可以使用以下方法急切加载array/hash的所有关联模型:

includes

我强烈建议您阅读Eager Loading Multiple Associations官方文档,其中包含一些明确的示例。