Skip to content

Commit 284bc23

Browse files
ikraamgmamhoff
authored andcommitted
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.
1 parent b6fbbe7 commit 284bc23

2 files changed

Lines changed: 12 additions & 0 deletions

File tree

legacy_promotions/app/models/spree/promotion.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,7 @@ def blacklisted?(promotable)
240240
when Spree::LineItem
241241
!promotable.variant.product.promotionable?
242242
when Spree::Order
243+
ActiveRecord::Associations::Preloader.new(records: promotable.line_items, associations: {variant: :product}).call
243244
promotable.line_items.any? { |line_item| !line_item.variant.product.promotionable? }
244245
end
245246
end

legacy_promotions/spec/models/spree/promotion_spec.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -714,6 +714,17 @@
714714
it { is_expected.to be true }
715715
end
716716
end
717+
718+
context "with several line items" do
719+
let(:promotion) { create(:promotion, :with_line_item_adjustment, apply_automatically: true) }
720+
let(:promotable) { create(:order_with_line_items, line_items_count: 3) }
721+
722+
before { promotable.reload }
723+
724+
it "loads line item variants in a single query" do
725+
expect { subject }.to make_database_queries(matching: /from .spree_variants..*\bid. IN \(/im, count: 1)
726+
end
727+
end
717728
end
718729

719730
context "when promotable is a Spree::LineItem" do

0 commit comments

Comments
 (0)