0
4

2 回答 2

3

您可以使用 rails 默认机制在查询中包含关联。此外,您应该在迭代大型数据集时使用 find_each。它分批获取对象,从而保护内存:

@users = User.includes(:account)

<% @users.find_each do | user | %>
  <%= user.account.name %>
<% end %>
于 2013-03-01T12:33:33.120 回答
1

它需要一段时间,因为@all_accounts = Account.where(:id => users.map{ | user | user.account_id } )实际上并没有运行该查询。查询在实际需要时运行,即当您调用detect.

它正在Account为每个用户运行查询,这显然是一个比原始查询更重要的查询,因为它Account每次都会拉大量 s,因此等待时间很长。

解决方案显然是做其他人推荐和使用的事情includes,但是坚持.all你的 s 查询的末尾Account也可以通过让该查询在第一个实例中执行来工作。

于 2013-03-01T13:42:18.970 回答