From f959e632eaeddfc450401509f5c3028e9b6ca2f3 Mon Sep 17 00:00:00 2001 From: Matt-Yorkley <9029026+Matt-Yorkley@users.noreply.github.com> Date: Tue, 7 Apr 2020 15:15:25 +0200 Subject: [PATCH] Modify Spree::Stock::Quantifier to not re-fetch stock items if they are already eager-loaded This helps to remove a big N+1 here, and will also be very helpful elsewhere in the app --- app/models/spree/stock/quantifier.rb | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/app/models/spree/stock/quantifier.rb b/app/models/spree/stock/quantifier.rb index 6b1c11de62..806fdf33dd 100644 --- a/app/models/spree/stock/quantifier.rb +++ b/app/models/spree/stock/quantifier.rb @@ -5,7 +5,7 @@ module Spree def initialize(variant) @variant = variant - @stock_items = Spree::StockItem.joins(:stock_location).where(:variant_id => @variant, Spree::StockLocation.table_name =>{ :active => true}) + @stock_items = fetch_stock_items end def total_on_hand @@ -23,6 +23,16 @@ module Spree def can_supply?(required) total_on_hand >= required || backorderable? end + + private + + def fetch_stock_items + # Don't re-fetch associated stock items from the DB if we've already eager-loaded them + return @variant.stock_items.to_a if @variant.stock_items.loaded? + + Spree::StockItem.joins(:stock_location). + where(:variant_id => @variant, Spree::StockLocation.table_name => { active: true }) + end end end end