ruby-on-rails - 通过 has_many 进行热切加载

标签 ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 eager-loading

我有一个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

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

您似乎只是想要与给定用户关联的个人资料计数。实现此目的的最佳方法是在 UserProfile 模型之间创建关联

用户 ==> has_many :profiles, through: :integration

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

另一个选项是(如果您不想使用上述选项)循环遍历所有集成并对每个集成的所有profiles.count求和.

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

关于ruby-on-rails - 通过 has_many 进行热切加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23459968/

相关文章:

ruby-on-rails - Rails - 从数据库 session 中分离模型

ruby-on-rails - 与另一个嵌套哈希相比,从嵌套哈希中查找丢失的键

ruby-on-rails - 在其他方法中访问循环变量

php - 在 ruby​​ 中使用 Blowfish 加密字符串返回的字符串比 php 中的相同进程更短

ruby-on-rails-3 - 保存到数据库时 JSON 中的多字节字符丢失

ruby-on-rails - Rails - 使用 PostgreSQL 安装 Cucumber

ruby-on-rails - Ruby (rails) 构造函数调用给出语法错误

javascript - jQuery - 丢失对 Ajax 刷新的表单的引用

javascript - 输入后需要获取coffeescript的数据

ruby-on-rails - 如何获取为特定模型类定义的所有 factory_girl 工厂?