Rails 4 ActiveRecord多个查询

时间:2016-02-10 04:36:47

标签: ruby-on-rails activerecord

我使用rails 4.2.5。 我在这段代码中遇到了某种N + 1问题

seats=SeatItem.where(:b => hall.id).all seats.each do |seat| arr << Ticket.new(:a => seat.id) end Ticket.import arr

这段代码的问题是我在日志中有这个

MIT 1 [["id", 13]] CACHE (0.0ms) SELECT "seat_item_types".* FROM "seat_item_types" WHERE "seat_item_types"."id" = $1 LIMIT 1 [["id", 13]] CACHE (0.0ms) SELECT "seat_item_types".* FROM "seat_item_types" WHERE "seat_item_types"."id" = $1 LIMIT 1 [["id", 13]] CACHE (0.0ms) SELECT "seat_item_types".* FROM "seat_item_types" WHERE "seat_item_types"."id" = $1 LIMIT 1 [["id", 13]] CACHE (0.0ms) SELECT "seat_item_types".* FROM "seat_item_types" WHERE "seat_item_types"."id" = $1 LIMIT 1 [["id", 13]] CACHE (0.0ms) SELECT "seat_item_types".* FROM "seat_item_types" WHERE "seat_item_types"."id" = $1 LIMIT 1 [["id", 13]] CACHE (0.0ms) SELECT "seat_item_types".* FROM "seat_item_types" WHERE "seat_item_types"."id" = $1 LIMIT 1 [["id", 13]] CACHE (0.0ms) SELECT "seat_item_types".* FROM "seat_item_types" WHERE "seat_item_types"."id" = $1 LIMIT 1 [["id", 13]] CACHE (0.0ms) SELECT "seat_item_types".* FROM "seat_item_types" WHERE "seat_item_types"."id" = $1 LIMIT 1 [["id", 13]] CACHE (0.0ms) SELECT "seat_item_types".* FROM "seat_item_types" WHERE "seat_item_types"."id" = $1 LIMIT 1 [["id", 13]] CACHE (0.0ms) SELECT "seat_item_types".* FROM "seat_item_types" WHERE "seat_item_types"."id" = $1 LIMIT 1 [["id", 13]] CACHE (0.0ms) SELECT "seat_item_types".* FROM "seat_item_types" WHERE "seat_item_types"."id" = $1 LIMIT 1 [["id", 13]] CACHE (0.0ms) SELECT "seat_item_types".* FROM "seat_item_types" WHERE "seat_item_types"."id" = $1 LIMIT 1 [["id", 13]] CACHE (0.0ms) SELECT "seat_item_types".* FROM "seat_item_types" WHERE

为什么:all方法不会在内存中加载所有内容以及如何修复它? 感谢您的投入!

2 个答案:

答案 0 :(得分:0)

您应该使用eager_load来解决N + 1查询问题

使用包括这样的方法

IEnumerable<IGrouping<string,object>>

http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations

但首先,我认为您在SeatItem和Ticket上定义关联 http://guides.rubyonrails.org/association_basics.html

答案 1 :(得分:0)

我认为var myapp = angular.module("myapp", []); myapp.controller("MyController", *function($scope, $interval)*{ $interval(callAtInterval, 5000); }); function callAtInterval() { console.log("Interval occurred"); } 不是问题所在。请注意,重复的SQL查询是相同的,并且它从:all而不是seat_item_types获取行。我的猜测是你有一个前/后钩子或其他一些由seat_itemsTicket.new触发Ticket.import的代码。