渴望通过has_many加载

Moh*_*awy 6 ruby-on-rails eager-loading ruby-on-rails-3 ruby-on-rails-4

我有一个User模特.

A user有很多integrations.

An integration连接到包含列的profilevia .integration_profilesdata

我想急切加载所有用户的个人资料.

class Integration < ActiveRecord::Base
 has_many :integration_profiles
 has_many :profiles, through: :integration_profiles
end

class IntegrationProfile < ActiveRecord::Base
 belongs_to :integration
 belongs_to :profile
end

class Profile < ActiveRecord::Base
 has_many :integration_profiles
 has_many :integrations, through: :integration_profiles
end
Run Code Online (Sandbox Code Playgroud)

我试过这个:

all = User.first.integrations.includes(:profiles)
Run Code Online (Sandbox Code Playgroud)

但是当我这样做的时候 all.count

=> 2
Run Code Online (Sandbox Code Playgroud)

但是,当我这样做

all = User.first.integrations.joins(:profiles)
all.count
=> the correct total
Run Code Online (Sandbox Code Playgroud)

我应该使用包含还是加入?我一直使用包括所以不确定为什么这不起作用

Kir*_*rat 3

当你这样做时

all = User.first.integrations.joins(:profiles)
all.count
Run Code Online (Sandbox Code Playgroud)

集成记录将计入第一个User,并在 上进行内部联接查询profiles

当你这样做时

all = User.first.integrations.includes(:profiles)
all.count
Run Code Online (Sandbox Code Playgroud)

您再次获得集成计数,但没有与配置文件连接查询,因为配置文件急切地加载了单独的查询,因为includes

看来您只是想要profiles与给定关联的计数user。实现这一目标的最佳方法是在UserProfile模型之间创建关联

User ==> has_many :profiles, through: :integration

完成此操作后,您可以直接访问User.first.profiles.count以获取特定用户的所有关联个人资料的计数。

另一个选项是(如果您不想使用上述选项)循环遍历所有内容integrations并总结profiles.count每个集成的所有内容。

选择最适合您需求的选项。