我已經包含client_person和case_histories,但是在查詢case_histories時它仍然會生成n + 1查詢。 我已經嘗試了很長時間,但似乎沒有任何工作。Rails急切加載不起作用(仍然是n + 1)
@client_records = @records.includes({person: [:client_person, :case_histories]})
在人模型: belongs_to :client_person, class_name: 'Client::Person' has_many :case_histories, through: :region_profiles, class_name: 'Admin::PeopleCaseHistory'
生成的n + 1中的查詢:
@client_records.each do |record|
record.person.case_histories.select{ |hist| hist.case_type == 2}.first
end
具體而言,後正確加載所有客戶端的case_histories在列表中(從包括所得子句),它仍然是每個客戶的case_histories的一個一個查詢。
由產生的第一查詢包括:
Admin::PeopleCaseHistory Load (46.9ms) SELECT "case_histories".* FROM "case_histories" WHERE "case_histories"."region_profile_id" IN (411, 16804, 572, 19506, 16539, 692, 4828)
隨後的N + 1的查詢:
Admin::PeopleCaseHistory Load (29.5ms) SELECT "case_histories".* FROM "case_histories" INNER JOIN "region_profiles" ON "case_histories"."region_profile_id" = "region_profiles"."id" WHERE "region_profiles"."person_id" = $1 [["person_id", 9867]]
Admin::PeopleCaseHistory Load (34.3ms) SELECT "case_histories".* FROM "case_histories" INNER JOIN "region_profiles" ON "case_histories"."region_profile_id" = "region_profiles"."id" WHERE "region_profiles"."person_id" = $1 [["person_id", 430]]
請指教! 謝謝
嘗試用'參考'替換'includes' – mdesantis
這不起作用 –
什麼是您看到的N + 1查詢重複? – Smudge