ActiveRecord的:包括 - 如何使用带有加载协会地图? [英] ActiveRecord :includes - how to use map with loaded associations?
问题描述
我有一个小的Rails应用程序,我试图得到一些订单的统计数据。 所以,我有一个管理模式,订单模式,有一个一对多的关联。
I have a small rails app, and I'm trying to get some order statistics. So I have an Admin model, and an Order model, with one-to-many association.
class Admin < ActiveRecord::Base
attr_accessible :name
has_many :orders
class Order < ActiveRecord::Base
attr_accessible :operation
belongs_to :admin
和我试图让使用此查询specifical命令:
And I'm trying to get specifical orders using this query:
admins = Admin.where(...).includes(:orders).where('orders.operation = ?', 'new gifts!')
这是如预期的工作而已。但是,当我尝试使用的地图一样,为了使JSON
That works just as expected. But when I try to make json using map like that
admins.map {|a| [a.name, a.orders.pluck(:operation)]}
Rails的负载再次令使用新的查询,忽略已加载的对象。
Rails loads orders again using new query, ignoring already loaded objects.
(5.6ms) SELECT "orders"."operation" FROM "orders" WHERE "orders"."admin_id" = 26
(6.8ms) SELECT "orders"."operation" FROM "orders" WHERE "orders"."admin_id" = 24
(2.9ms) SELECT "orders"."operation" FROM "orders" WHERE "orders"."admin_id" = 30
(3.3ms) SELECT "orders"."operation" FROM "orders" WHERE "orders"."admin_id" = 29
(4.8ms) SELECT "orders"."operation" FROM "orders" WHERE "orders"."admin_id" = 27
(3.3ms) SELECT "orders"."operation" FROM "orders" WHERE "orders"."admin_id" = 28
(5.1ms) SELECT "orders"."operation" FROM "orders" WHERE "orders"."admin_id" = 25
当我尝试使用 循环而不是地图,它的作品,因为它应该:
When I try to use loop instead of map, it works as it should:
admins.each do |a|
p a.orders.pluck(:operation)
end
这code不加载所有的订单,并打印只在第一个查询加载。 是否有可能使用的地图,以获得相同的结果?什么是使用循环而不是地图的缺点?
this code doesn't load all orders, and prints only those loaded in the first query. Is it possible to get the same result using map? What are the drawbacks of using loop instead of map?
推荐答案
勇气
应该总是让一个新的查询数据库。不知道为什么你认为它不会发生在每个
循环。也许你没有看到日志,因为它是在打印的?
pluck
should always make a new query to database. Not sure why you think it does not happen in an each
loop. Maybe you did not see the log because it is in between your prints?
有两种可能性如何避免额外的查询。
There are 2 possibilities how to avoid additional queries.
-
既然已经装订单,因为你有他们,你可以做
admins.map {| A | [a.name,a.orders.collect(安培;:操作)]}
使用联接(见@ tihom的评论)。
Using joins (see @tihom's comment).
编辑:我只是测试了每个
/ 地图
的行为,并重新加载每次按预期时间
I just tested the each
/ map
behavior and it reloads every time as expected.
这篇关于ActiveRecord的:包括 - 如何使用带有加载协会地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!