ruby-on-rails – 渴望通过has_many加载
发布时间:2020-12-16 21:01:58 所属栏目:百科 来源:网络整理
导读:我有一个用户模型. 用户有许多集成. 集成通过包含列数据的integration_profiles连接到配置文件. 我想急切加载所有用户的个人资料. class Integration ActiveRecord::Base has_many :integration_profiles has_many :profiles,through: :integration_profiles
我有一个用户模型.
用户有许多集成. 集成通过包含列数据的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) 但是当我做所有的时候我 => 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 再次,你得到集合计数BUT没有连接查询与配置文件,因为配置文件由于包括急切加载单独的查询 您似乎只想要与给定用户关联的配置文件计数.实现此目的的最佳方法是在User和Profile模型之间创建关联 用户==> has_many:profiles,通过:: integration 完成后,您可以直接访问User.first.profiles.count以获取特定用户的所有关联配置文件的计数. 另一个选项是(如果你不想使用上面的选项)循环所有集成并总结每个集成的所有profiles.count. 选择最适合您需求的选项. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |