【问题标题】:Active Record eager load across models跨模型的 Active Record 急切加载
【发布时间】:2015-08-22 15:35:34
【问题描述】:

鉴于以下模型,我怎样才能急切地加载医生专业,以免陷入循环?现在我可以加载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

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

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

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

    in this answerJoe Kennedy所示。

    【讨论】:

    • 如果有人有模型的命名空间类,这将失败。 { DoctorProfile: :specialty } 不起作用。你必须使用:{ doctor_profile: :specialty }
    【解决方案2】:

    Active Record 允许您使用 Model.where/Model.find 调用 arrayhasharray/hashnested hashincludes 方法,将 eager load 与单个 Model.where/Model.find 调用关联起来。

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

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

    我强烈建议您阅读Eager Loading Multiple Associations 官方文档,该文档通过一些清晰的示例对其进行了解释。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-08
      • 2013-06-10
      相关资源
      最近更新 更多