我的目标是为给定集合的每个模型对象导出投票。在此示例中,我使用 .all,但在野外,它将是产生大集合的 .where。我有以下我担心的查询:
Model.all.each{|x|puts x.votes.count}.explain
(0.4ms) SELECT COUNT(*) FROM `votes` WHERE `votes`.`entry_id` = 1
0
(0.3ms) SELECT COUNT(*) FROM `votes` WHERE `votes`.`entry_id` = 2
0
(0.4ms) SELECT COUNT(*) FROM `votes` WHERE `votes`.`entry_id` = 3
1
(0.3ms) SELECT COUNT(*) FROM `votes` WHERE `votes`.`entry_id` = 4
0
(0.2ms) SELECT COUNT(*) FROM `votes` WHERE `votes`.`entry_id` = 5
0
单独计数非常快,但我觉得调用 All 不太舒服,尤其是当我有数千或数百万的集合时。有没有办法将记录计为批量操作?