Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Add `Product#variant_count` counter cache (#13469)
Damian Legawiec4887984e8120
diff --git a/api/spec/serializers/spree/api/v2/platform/product_serializer_spec.rb b/api/spec/serializers/spree/api/v2/platform/product_serializer_spec.rbindex 1b5870dcfb..bfa0659665 100644--- a/api/spec/serializers/spree/api/v2/platform/product_serializer_spec.rb+++ b/api/spec/serializers/spree/api/v2/platform/product_serializer_spec.rb@@ -49,6 +49,7 @@ describe Spree::Api::V2::Platform::ProductSerializer dodisplay_price: '$10.00',compare_at_price: BigDecimal(15),display_compare_at_price: '$15.00',+ variant_count: product.variant_count,public_metadata: {},private_metadata: {}},diff --git a/core/app/models/spree/product.rb b/core/app/models/spree/product.rbindex acd34f5f82..ca104323b4 100644--- a/core/app/models/spree/product.rb+++ b/core/app/models/spree/product.rb@@ -41,7 +41,7 @@ module SpreeMEMOIZED_METHODS = %w[total_on_hand taxonomy_ids taxon_and_ancestors categorydefault_variant_id tax_category default_variantdefault_image secondary_image- purchasable? in_stock? backorderable? has_variants? digital?]+ purchasable? in_stock? backorderable? digital?]STATUSES = %w[draft active archived].freeze@@ -311,9 +311,13 @@ module Spreemaster || build_masterend- # the master variant is not a member of the variants array+ # Checks if product has variants (non-master variants)+ # Uses variant_count counter cache for performance+ # @return [Boolean]def has_variants?- @has_variants ||= variants.loaded? ? variants.size.positive? : variants.any?+ return variants.size.positive? if variants.loaded?++ variant_count.positive?end# Returns default Variant for Productdiff --git a/core/app/models/spree/variant.rb b/core/app/models/spree/variant.rbindex 01ccb9e2a5..41ad75875a 100644--- a/core/app/models/spree/variant.rb+++ b/core/app/models/spree/variant.rb@@ -82,6 +82,8 @@ module Spreeafter_commit :remove_prices_from_master_variant, on: [:create, :update], unless: :is_master?after_commit :remove_stock_items_from_master_variant, on: :create, unless: :is_master?+ after_create :increment_product_variant_count, unless: :is_master?+ after_destroy :decrement_product_variant_count, unless: :is_master?after_touch :clear_in_stock_cache@@ -684,5 +686,13 @@ module Spreedef remove_stock_items_from_master_variantproduct.master.stock_items.delete_allend++ def increment_product_variant_count+ Spree::Product.increment_counter(:variant_count, product_id)+ end++ def decrement_product_variant_count+ Spree::Product.decrement_counter(:variant_count, product_id)+ endendenddiff --git a/core/db/migrate/20260118120000_add_statistics_to_store_products.rb b/core/db/migrate/20260118120000_add_statistics_to_store_products.rbindex 03e8d80ac7..4fb5af76c9 100644--- a/core/db/migrate/20260118120000_add_statistics_to_store_products.rb+++ b/core/db/migrate/20260118120000_add_statistics_to_store_products.rb@@ -1,11 +1,11 @@class AddStatisticsToStoreProducts < ActiveRecord::Migration[7.0]def change- add_column :spree_products_stores, :units_sold_count, :integer, default: 0, null: false- add_column :spree_products_stores, :revenue, :decimal, precision: 10, scale: 2, default: 0, null: false+ add_column :spree_products_stores, :units_sold_count, :integer, default: 0, null: false, if_not_exists: true+ add_column :spree_products_stores, :revenue, :decimal, precision: 10, scale: 2, default: 0, null: false, if_not_exists: trueadd_index :spree_products_stores, [:store_id, :units_sold_count],- name: 'index_products_stores_on_store_and_units_sold'+ name: 'index_products_stores_on_store_and_units_sold', if_not_exists: trueadd_index :spree_products_stores, [:store_id, :revenue],- name: 'index_products_stores_on_store_and_revenue'+ name: 'index_products_stores_on_store_and_revenue', if_not_exists: trueendenddiff --git a/core/db/migrate/20260119120000_add_variant_count_to_spree_products.rb b/core/db/migrate/20260119120000_add_variant_count_to_spree_products.rbnew file mode 100644index 0000000000..1454df9b66--- /dev/null+++ b/core/db/migrate/20260119120000_add_variant_count_to_spree_products.rb@@ -0,0 +1,6 @@+class AddVariantCountToSpreeProducts < ActiveRecord::Migration[7.2]+ def change+ add_column :spree_products, :variant_count, :integer, default: 0, null: false, if_not_exists: true+ add_index :spree_products, :variant_count, if_not_exists: true+ end+enddiff --git a/core/lib/tasks/product_metrics.rake b/core/lib/tasks/products.rakesimilarity index 58%rename from core/lib/tasks/product_metrics.rakerename to core/lib/tasks/products.rakeindex e46ec41a14..9fa109272c 100644--- a/core/lib/tasks/product_metrics.rake+++ b/core/lib/tasks/products.rake@@ -1,5 +1,14 @@namespace :spree do- namespace :product_metrics do+ namespace :products do+ desc 'Reset variant_count counter cache on products'+ task reset_variant_count: :environment do |_t, _args|+ puts 'Resetting variant_count counter cache...'+ Spree::Product.in_batches.update_all(+ "variant_count = (SELECT COUNT(*) FROM spree_variants WHERE spree_variants.product_id = spree_products.id AND spree_variants.is_master = false AND spree_variants.deleted_at IS NULL)"+ )+ puts 'Done!'+ end+desc 'Enqueue background jobs to populate product metrics for all store products'task populate: :environment dototal_count = 0diff --git a/core/spec/models/spree/image_spec.rb b/core/spec/models/spree/image_spec.rbindex c5f74f9a2a..e406a36f97 100644--- a/core/spec/models/spree/image_spec.rb+++ b/core/spec/models/spree/image_spec.rb@@ -61,6 +61,7 @@ describe Spree::Image, type: :model dolet(:viewable) { product.reload.master }it 'touches product variants' do+ image.viewable.product.reloadexpect(image).to receive(:touch_product_variants)image.set_list_position(2)enddiff --git a/core/spec/models/spree/product_spec.rb b/core/spec/models/spree/product_spec.rbindex ad41441c7f..a7c591f6db 100644--- a/core/spec/models/spree/product_spec.rb+++ b/core/spec/models/spree/product_spec.rb@@ -1548,4 +1548,43 @@ describe Spree::Product, type: :model doendend+ describe '#has_variants?' do+ let(:product) { create(:product, stores: [store]) }++ context 'without variants' do+ it 'returns false' do+ expect(product.has_variants?).to be false+ end++ it 'has variant_count of 0' do+ expect(product.variant_count).to eq 0+ end+ end++ context 'with variants' do+ before { create(:variant, product: product) }++ it 'returns true' do+ expect(product.reload.has_variants?).to be true+ end++ it 'has variant_count of 1' do+ expect(product.reload.variant_count).to eq 1+ end+ end++ context 'when variants are loaded in memory' do+ let(:product) { create(:product, stores: [store]) }++ before do+ create(:variant, product: product)+ product.reload+ product.variants.load+ end++ it 'uses the loaded association instead of variant_count' do+ expect(product.has_variants?).to be true+ end+ end+ endenddiff --git a/core/spec/models/spree/variant_spec.rb b/core/spec/models/spree/variant_spec.rbindex 6d9fa65525..f72007ba48 100644--- a/core/spec/models/spree/variant_spec.rb+++ b/core/spec/models/spree/variant_spec.rb@@ -1422,4 +1422,33 @@ describe Spree::Variant, type: :model doexpect(variant.additional_images).to eq([image2, image3])endend++ describe 'counter cache' do+ let(:product) { create(:product) }++ describe 'variant_count on product' do+ it 'increments when a variant is created' do+ expect {+ create(:variant, product: product)+ }.to change { product.reload.variant_count }.from(0).to(1)+ end++ it 'decrements when a variant is destroyed' do+ variant = create(:variant, product: product)+ expect {+ variant.destroy+ }.to change { product.reload.variant_count }.from(1).to(0)+ end++ it 'does not count master variant' do+ expect(product.variant_count).to eq(0)+ expect(product.master).to be_present+ end++ it 'correctly counts multiple variants' do+ create_list(:variant, 3, product: product)+ expect(product.reload.variant_count).to eq(3)+ end+ end+ endend