Ruby on rails 急切地装载已通过许多
我有一个Ruby on rails 急切地装载已通过许多,ruby-on-rails,ruby-on-rails-3,ruby-on-rails-4,eager-loading,Ruby On Rails,Ruby On Rails 3,Ruby On Rails 4,Eager Loading,我有一个用户模型 一个用户有许多集成 integration通过integration\u profiles连接到profile,其中包含一列数据 我想加载用户的所有配置文件 class Integration < ActiveRecord::Base has_many :integration_profiles has_many :profiles, through: :integration_profiles end class IntegrationProfile < A
用户
模型
一个用户
有许多集成
integration
通过integration\u profiles
连接到profile
,其中包含一列数据
我想加载用户的所有配置文件
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.count时
=> 2
但当我这么做的时候
all = User.first.integrations.joins(:profiles)
all.count
=> the correct total
我应该使用包含还是连接?我一直使用includes,所以不确定为什么这里不起作用
all=User.first.integrations.includes(:profiles)
all.count
返回的是集成计数,而不是配置文件计数。配置文件被急切地加载
如果您想知道配置文件的计数,则需要以这种方式完成
ar = [ ]
all.each do |a|
ar << a.profiles.count
end
ar=[]
每个人都做一件事|
当你这样做的时候
all = User.first.integrations.joins(:profiles)
all.count
all = User.first.integrations.includes(:profiles)
all.count
对于第一个用户
和配置文件
上的内部联接查询,将统计集成记录
当你这么做的时候
all = User.first.integrations.joins(:profiles)
all.count
all = User.first.integrations.includes(:profiles)
all.count
同样,您可以获得集成计数,但不使用配置文件进行连接查询,因为由于包含
似乎您只是想要与给定的用户关联的配置文件
计数。实现这一点的最佳方法是,在用户
和配置文件
模型之间创建关联
User==>通过::集成拥有多个:配置文件
完成此操作后,您可以直接访问User.first.profiles.count
,以获取特定用户的所有关联配置文件的计数
另一个选项是(如果您不想使用上述选项)循环所有集成
,并汇总所有配置文件。对每个集成进行计数
选择最适合您需要的选项。好的,我想进行即时加载,这样我可以调用用户。首先,profiles
,我如何才能以这种方式进行即时加载?嗨@KirtiThorat,我如何能够向后调用或选择连接集成和概要的关节模型?