嵌套关联中的预先加载

时间:2016-06-03 03:58:29

标签: ruby-on-rails ruby-on-rails-4

我有4个模特:

class Profile < ActiveRecord::Base
  has_many :profile_profile_categories, dependent: :destroy
  has_many :profile_categories, through: :profile_profile_categories
end

class ProfileCategory < ActiveRecord::Base
  belongs_to :profile_subject
end

class ProfileSubject < ActiveRecord::Base
  has_many :profile_categories, dependent: :destroy
end

class ProfileProfileCategory < ActiveRecord::Base
  belongs_to :profile_category
  belongs_to :profile
end

如何加载Profile和eager load ProfileCategory和ProfileSubject?

Profile.includes(profile_categories: :profile_subject)无法正常工作。

Gem bullet在浏览器中显示下一个通知:

user: verrom N+1 Query detected ProfileSubject => [:profile_categories] Add to your finder: :includes => [:profile_categories]

在服务器日志中,我可以看到很多关于表ProfileCategory的查询,如:

ProfileCategory Load (2.6ms)  SELECT "profile_categories".* FROM "profile_categories" WHERE "profile_categories"."profile_subject_id" = $1  [["profile_subject_id", 4]]

由于

2 个答案:

答案 0 :(得分:0)

在下面尝试一次

Profile.includes(profile_profile_categories: [{ profile_category: :profile_subject } ], :profile_categories)

答案 1 :(得分:0)

从SQL日志中可以正确加载ProfileSubject。添加你从bullet gem中看到的东西。

Profile.includes(:profile_categories, profile_categories: :profile_subject)

这应该有效