大佬教程收集整理的这篇文章主要介绍了ruby-on-rails – 渴望通过has_many加载,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
用户有许多集成.
集成通过包含列数据的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 @R_6_10586@l
@R_548_10675@用包含还是加入?我一直使用包括所以不确定为什么这不起作用
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.
选择最适合您需求的选项.
以上是大佬教程为你收集整理的ruby-on-rails – 渴望通过has_many加载全部内容,希望文章能够帮你解决ruby-on-rails – 渴望通过has_many加载所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。