Rails 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
请注意,在我的log
中,商店ID为26,23,22的最后3行是多余的。我应该如何重写cities_controller.rb
以减少对系统的查询?
非常感谢。
答案 0 :(得分:2)
@zones = @trip.zones.includes(:shops).order("position")
这会急切加载商店协会,并且应该消除由zone.shops.each
有关更多信息,请查看Ruby on Rails Guide section 12 on Eager Loading associations,该链接也由@Benjamin M链接
答案 1 :(得分: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
这很简单,简单明了:)