From 434f98fb4693c796fb808fa292fe4e20ffaaff05 Mon Sep 17 00:00:00 2001 From: Matt-Yorkley <9029026+Matt-Yorkley@users.noreply.github.com> Date: Mon, 23 Mar 2020 17:16:33 +0100 Subject: [PATCH] Fix insane N+1 in Package The #ships_with? method was being called ~800 times when loading the admin order edit page (with Aus production data), and triggering a new query each time it was called. --- app/models/stock/package.rb | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/app/models/stock/package.rb b/app/models/stock/package.rb index 75f6b30261..ffa76ffa72 100644 --- a/app/models/stock/package.rb +++ b/app/models/stock/package.rb @@ -24,8 +24,10 @@ module Stock # # @return [Array] def shipping_methods - super.delete_if do |shipping_method| - !ships_with?(order.distributor, shipping_method) + available_shipping_methods = super.to_a + + available_shipping_methods.delete_if do |shipping_method| + !ships_with?(order.distributor.shipping_methods.to_a, shipping_method) end end @@ -33,11 +35,11 @@ module Stock # Checks whether the given distributor provides the specified shipping method # - # @param distributor [Spree::Enterprise] + # @param shipping_methods [Array] # @param shipping_method [Spree::ShippingMethod] # @return [Boolean] - def ships_with?(distributor, shipping_method) - distributor.shipping_methods.include?(shipping_method) + def ships_with?(shipping_methods, shipping_method) + shipping_methods.include?(shipping_method) end end end