From 100334477cf810d063731d8a3a595f77c0c0c1d1 Mon Sep 17 00:00:00 2001 From: Ikraam Ghoor Date: Fri, 26 Jun 2026 07:13:55 +0200 Subject: [PATCH] Preload variants when checking order promotionability Checking whether an order contains a non-promotionable product loaded each line item's variant and product with a query per line item. This runs every time a promotion's eligibility is evaluated. Preloading the variant and product for all line items keeps that load constant regardless of how many items the order has. --- legacy_promotions/app/models/spree/promotion.rb | 1 + legacy_promotions/spec/models/spree/promotion_spec.rb | 11 +++++++++++ 2 files changed, 12 insertions(+) diff --git a/legacy_promotions/app/models/spree/promotion.rb b/legacy_promotions/app/models/spree/promotion.rb index 0b81e554b45..66c234fb967 100644 --- a/legacy_promotions/app/models/spree/promotion.rb +++ b/legacy_promotions/app/models/spree/promotion.rb @@ -240,6 +240,7 @@ def blacklisted?(promotable) when Spree::LineItem !promotable.variant.product.promotionable? when Spree::Order + ActiveRecord::Associations::Preloader.new(records: promotable.line_items, associations: {variant: :product}).call promotable.line_items.any? { |line_item| !line_item.variant.product.promotionable? } end end diff --git a/legacy_promotions/spec/models/spree/promotion_spec.rb b/legacy_promotions/spec/models/spree/promotion_spec.rb index 441d4cab20c..846dd2c526b 100644 --- a/legacy_promotions/spec/models/spree/promotion_spec.rb +++ b/legacy_promotions/spec/models/spree/promotion_spec.rb @@ -714,6 +714,17 @@ it { is_expected.to be true } end end + + context "with several line items" do + let(:promotion) { create(:promotion, :with_line_item_adjustment, apply_automatically: true) } + let(:promotable) { create(:order_with_line_items, line_items_count: 3) } + + before { promotable.reload } + + it "loads line item variants in a single query" do + expect { subject }.to make_database_queries(matching: /from .spree_variants..*\bid. IN \(/im, count: 1) + end + end end context "when promotable is a Spree::LineItem" do