Rails 3.2。我有以下幾點:在我log
,最後3行與ID 26,23店優化Rails中的熱切加載
# 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
通知,22是多餘的。我應該如何重寫我的cities_controller.rb
以減少對系統的查詢?
非常感謝。
Btw :':include => ... [:shops]])''''''''''''''''''''''''''''''''''''''''''因爲include的作用域是'@ trip',但是你正在循環'@ zones', '包括()'在 – emrass 2013-02-27 16:25:55
您的解決方案爲以下項目創建緩存版本:** ZoneShop載入(0.3ms)SELECT'zone_shops'。*從'zone_shops'在哪裏'zone_shops'.'zone_id' IN(26,23,22)令(8,7,1,9)**,這可以正常工作。只是一個問題,是否有可能完全消除緩存? – Victor 2013-02-27 16:28:01
你會如何改寫'show'? – Victor 2013-02-27 16:29:24