2

导轨 3.2。我有以下内容:

# city.rb
class City < ActiveRecord::Base
  has_many :zones, :dependent => :destroy
end

# zone.rb
class Zone < ActiveRecord::Base
  belongs_to :city
  has_many :zone_shops, :dependent => :destroy
  has_many :shops, :through => :zone_shops
end

# zone_shop.rb
class ZoneShop < ActiveRecord::Base
  belongs_to :zone
  belongs_to :shop
end

# shop.rb
class Shop < ActiveRecord::Base
end

# cities_controller.rb
def show
  @trip = City.find(params[:id], :include => [:user, :zones => [:shops]])
  @zones = @trip.zones.order("position")

  # List out all shops for the trip
  shops_list_array = []
  @zones.each do |zone, i|
    zone.shops.each do |shop|
      shops_list_array << shop.name
    end
  end
  @shops_list = shops_list_array.join(', ')
end

# development.log
  City Load (0.3ms)  SELECT `cities`.* FROM `cities` WHERE `cities`.`id` = 1 LIMIT 1
  Zone Load (0.3ms)  SELECT `zones`.* FROM `zones` WHERE `zones`.`trip_id` IN (1) ORDER BY position asc
  ZoneShop Load (0.3ms)  SELECT `zone_shops`.* FROM `zone_shops` WHERE `zone_shops`.`zone_id` IN (26, 23, 22) ORDER BY position asc
  Shop Load (0.5ms)  SELECT `shops`.* FROM `shops` WHERE `shops`.`id` IN (8, 7, 1, 9)
  Zone Load (0.5ms)  SELECT `zones`.* FROM `zones` WHERE `zones`.`trip_id` = 1 ORDER BY position asc, position
  Shop Load (0.5ms)  SELECT `shops`.* FROM `shops` INNER JOIN `zone_shops` ON `shops`.`id` = `zone_shops`.`spot_id` WHERE `zone_shops`.`zone_id` = 26
  Shop Load (0.6ms)  SELECT `shops`.* FROM `shops` INNER JOIN `zone_shops` ON `shops`.`id` = `zone_shops`.`spot_id` WHERE `zone_shops`.`zone_id` = 23
  Shop Load (0.4ms)  SELECT `shops`.* FROM `shops` INNER JOIN `zone_shops` ON `shops`.`id` = `zone_shops`.`spot_id` WHERE `zone_shops`.`zone_id` = 22

请注意,在 mylog中,ID 为 26、23、22 的商店的最后 3 行是多余的。我应该如何重写我cities_controller.rb的以减少对系统的查询?

非常感谢。

4

2 回答 2

2
@zones = @trip.zones.includes(:shops).order("position")

这会立即加载商店关联,并应消除由以下原因引起的 n+1 查询问题zone.shops.each

有关更多信息,请查看Ruby on Rails 指南第 12 节关于 Eager Loading 关联的内容,该链接也由 @Benjamin M 链接

于 2013-02-27T16:19:14.807 回答
0

我建议这个

zone.shops.each do |shop|
  shops_list_array << shop.name
end

生成日志的最后 3 行。这意味着:您的数据库中目前只有一个zone。如果您在其中放置更多区域,您将在日志中获得更多Zone Load条目。

问题显然是 Rails 的each方法,它触发了延迟加载:

@zones.each do |zone, i|
  ...

解决方案取决于您的需求,但我建议您阅读有关 Rails 急切加载功能的所有内容。(这正是你的问题:each事情)。在这里查找:http: //guides.rubyonrails.org/active_record_querying.html#eager-loading-associations

这很简单,简短而直接:)

于 2013-02-27T15:45:30.293 回答