我有一个User
模型。
一个用户
有许多集成
。
集成
通过包含数据
列的integration_profiles
连接到配置文件
。
我想立即加载所有用户的个人资料。
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
我试过这个:
all = User.first.integrations.includes(:profiles)
但是当我这样做时all.count
=> 2
但是当我这样做时
all = User.first.integrations.joins(:profiles)
all.count
=> the correct total
我应该使用包含还是联接?我一直使用包含所以不知道为什么这在这里不起作用
最佳答案
当你这样做时
all = User.first.integrations.joins(:profiles)
all.count
集成记录将针对第一个用户
进行计数,并在个人资料
上进行内部联接查询。
当你这样做时
all = User.first.integrations.includes(:profiles)
all.count
您再次获得集成计数,但没有与配置文件连接查询,因为由于包含
,配置文件急切地加载了单独的查询
您似乎只是想要与给定用户
关联的个人资料
计数。实现此目的的最佳方法是在 User
和 Profile
模型之间创建关联
用户 ==> has_many :profiles, through: :integration
完成此操作后,您可以直接访问 User.first.profiles.count
以获取特定用户的所有关联个人资料的计数。
另一个选项是(如果您不想使用上述选项)循环遍历所有集成
并对每个集成的所有profiles.count
求和.
选择最适合您需求的选项。
关于ruby-on-rails - 通过 has_many 进行热切加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23459968/