From d3af3d3f27dd1df9ab7f55e1191eb3d01fff7724 Mon Sep 17 00:00:00 2001 From: Matt-Yorkley <9029026+Matt-Yorkley@users.noreply.github.com> Date: Tue, 28 Apr 2020 01:15:10 +0200 Subject: [PATCH] Avoid extra query on stock_items every time #on_demand is called on a variant. In the case where the variant has not been saved yet, we can use #new_record? here instead of #stock_items.empty?, to avoid an additional query. This can be called a vast number of times per request, in various N+1s. The other case where we need to return here is when a variant has been deleted, so #stock_items will be empty and #stock_item will be nil. Likewise, we can just check that with #deleted? and avoid #stock_items.empty? --- app/models/concerns/variant_stock.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/models/concerns/variant_stock.rb b/app/models/concerns/variant_stock.rb index 1cc0ec4e04..5a6094adf4 100644 --- a/app/models/concerns/variant_stock.rb +++ b/app/models/concerns/variant_stock.rb @@ -40,9 +40,9 @@ module VariantStock # Checks whether this variant is produced on demand. def on_demand - # A variant that has not been saved yet, doesn't have a stock item + # A variant that has not been saved yet or has been soft-deleted doesn't have a stock item # This provides a default value for variant.on_demand using Spree::StockLocation.backorderable_default - return Spree::StockLocation.first.backorderable_default if stock_items.empty? + return Spree::StockLocation.first.backorderable_default if new_record? || deleted? stock_item.backorderable? end