簡體   English   中英

Rails eager_load 實例上的深度關聯

[英]Rails eager_load deep associations on an instance

以下是我的五個模型和相關協會:

class User < ActiveRecord::Base
  has_many :answers
end    

class Answer < ActiveRecord::Base
  belongs_to :question
end

class Question < ActiveRecord::Base
  belongs_to :sub_category
end

class SubCategory < ActiveRecord::Base
  belongs_to :super_category
end

class SuperCategory < ActiveRecord::Base
  has_many :sub_categories
end

接下來我找到一個User object:

@user = User.find(1234)

現在我想做的是 eager_load 以下內容:

  • 用戶的所有Answers
    • 每個答案的相關question
      • 每個問題的相關sub_category
        • 每個 sub_categories 的關聯super_category

我嘗試了以下操作:

@user.eager_load(answers: {question: {sub_category: :super_category}})

但是它返回以下錯誤:

NoMethodError ... [用戶記錄] 的未定義方法“eager_load”

我不確定我做錯了什么。

問題:如何在實例上 eager_load 上面的關聯?

我不確定這是否重要:但在執行所有 eager_loading 時:沒有任何相關的question記錄被保留,所以它們的所有ids都是 nil。 我認為這不重要,但以防萬一:我想我應該提一下。

您試圖阻止N + 1查詢。

預加載為每個集合執行單獨的SQL查詢。

熱切的負載構造了一個左連接的SELECT,以在一個查詢中檢索所有集合。 如果使用includes Rails,請選擇要使用的那個。

eager_load是一個類方法。 您應該在模型Class上使用。

嘗試這樣:

User.eager_load(answers: {question: {sub_category: :super_category}}).where("users.id = ?",1).first 

要么

User.eager_load(answers: {question: {sub_category: :super_category}}).find(1)

正如Awlad在評論中建議的那樣,應該在類而不是實例上調用eager_load 請參閱文檔 做得好,Awlad!

例如,值得嘗試preload ...... 看看文檔

假設,

#share is polymorphic
#share is created by user

share ||= shared.tap do |share|
  ::ActiveRecord::Associations::Preloader.new.preload(share, [:user, :shareable])
end

或者,使用includes

Share.includes(:user, :shareable).find(share.id)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM