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 default_variant_id and master-variant retirement task
Łukasz Adamczyk1f211bd47d1f
diff --git a/docs/plans/6.0-remove-master-variant.md b/docs/plans/6.0-remove-master-variant.mdindex 3939cf58ab..8bca6d315d 100644--- a/docs/plans/6.0-remove-master-variant.md+++ b/docs/plans/6.0-remove-master-variant.md@@ -1,10 +1,10 @@# Remove Master Variant-**Status:** Design finalized, implementation not started+**Status:** Design finalized. Phase 4 (API) partially shipped — public serializer/controller surface migrated to `default_variant`; internal API-layer cleanup + backend Phases 1–3 + data migration pending.**Target:** Spree 6.0**Depends on:** None (standalone, but coordinate with Cart/Order split)**Author:** Damian + Claude-**Last updated:** 2026-03-16+**Last updated:** 2026-06-30## Summary@@ -32,9 +32,11 @@ No other modern commerce platform uses this pattern. The industry standard is: e| Pattern | Occurrences | Files ||---------|------------|-------|-| `is_master` references | 32 | 13 |-| `variants_including_master` | 35 | 13 |-| `.master` on product (app + specs) | 255 | 50 |+| `is_master` references (app code) | 37 | 13 |+| `variants_including_master` (app code) | 38 | 16 |+| `.master` on product | 26 app + 269 spec | ~65 |++_Counts re-verified 2026-06-30. `variants_including_master` grew to 16 app files since the original count — new consumers include the media controller, product finders/sorters, data-feed + search presenters, and a dashboard e2e setup._## Key Decisions (do not deviate without discussion)@@ -171,18 +173,21 @@ end### API changes+**Status: the public API surface is already migrated.** There is no `master_variant` expand key+anywhere in the v3 API — `ProductSerializer` ships `default_variant_id` plus a `one :default_variant`+expand, and Store + Admin serializers read `price`/`original_price`/`prior_price` from+`product.default_variant`. The admin products controller already accepts `variants: [...]` nested+attributes and a top-level `prices` convenience that forwards to the default variant via+`Spree::Product#prices=`. The originally-planned `expand=master_variant` deprecation alias was never+needed and does not exist.+```ruby-# Product serializer-# Before:-one :master, key: :master_variant, ...-# After:+# Product serializer — current (shipped) stateone :default_variant, resource: Spree.api.variant_serializer,if: proc { expand?('default_variant') }--# Deprecation alias: expand=master_variant still works for one release```-Store API response — `default_variant_id` replaces `master_variant`:+Store API response — already returns `default_variant_id`, no `master_variant`:```json{"id": "prod_86Rf07xd4z",@@ -194,6 +199,13 @@ Store API response — `default_variant_id` replaces `master_variant`:}```+**Internal API-layer cleanup still owed (Phase 4 is partial, not done).** These call the master under+the hood and must be retired alongside the model changes:++- `scope_includes` eager-loads `master: [...]` in both the Store and Admin products controllers — drop once `variants` returns all variants.+- The admin variants controller uses `parent_association: :variants_including_master` — becomes `:variants`.+- `media_controller.rb` references `@product.master&.id` / `variants_including_master` as the legacy master-pinned-media bridge (see Edge Cases).+### What stays the same- **LineItem `belongs_to :variant`** — unchanged@@ -241,11 +253,11 @@ This task must be **idempotent** and **reversible** (soft — we can't re-create### Phase 3: Model changes-1. Remove `is_master` column from `spree_variants`-2. Remove `has_one :master` from Product-3. Remove `has_many :variants_including_master` from Product+1. Deprecate the `is_master` column — keep it in `spree_variants` until Phase 5/6.1+2. Replace `has_one :master` with a deprecated `master` method returning `default_variant` (removed in Phase 5/6.1)+3. Replace `has_many :variants_including_master` with a deprecated method returning the `variants` relation (removed in Phase 5/6.1); move `dependent: :destroy` + `order(:position)` onto `variants`4. Change `has_many :variants` to remove `where(is_master: false)` filter-5. Add `belongs_to :default_variant` on Product+5. Add `belongs_to :default_variant` (backed by the new `default_variant_id` column) on Product, and **remove the existing computed `default_variant` / `default_variant_id` methods** (`product.rb:367-379`) so the FK column/association takes over — otherwise they collide. Behavior change to reconcile: today `default_variant` is _stock-aware_ (returns the first purchasable variant), so the displayed price/SKU follows stock; the FK makes the default _sticky_ (auto-promote only on delete/discontinue). See Open Questions.6. Update all delegations to use `default_variant`7. Remove ghost callbacks from Variant8. Remove `option_value_variants` presence validation@@ -263,8 +275,8 @@ This task must be **idempotent** and **reversible** (soft — we can't re-create### Phase 5: Cleanup (6.1)- Remove `is_master` column migration-- Remove deprecation aliases (`master_variant` expand, `variants_including_master`)-- Remove `master` method from Product+- Remove the deprecated `variants_including_master` method (no `master_variant` expand alias exists to remove — it was never added)+- Remove the deprecated `master` method from Product## Edge Cases@@ -277,6 +289,15 @@ LineItems in completed orders may reference the old master variant. Two options:**Decision: (a).** Former masters with line items survive as regular variants. They just lose the `is_master` flag. The `default_variant_id` points to the first real variant (or to this converted master for simple products).+### Legacy master-pinned media++The product media system (`5.5-6.0-product-media-system`) introduced product-level media but kept a backward-compat path for **assets historically pinned to the master variant**. Several consumers now read master specifically for this:++- `media_controller.rb` surfaces both product-level assets and legacy master-pinned assets (`@product.master&.id`, `variants_including_master`) so existing data keeps showing during migration.+- `jobs/spree/media/migrate_product_assets_job.rb` and `asset.rb` branch on master / `is_master`.++When master is removed, the data migration must **reattach any master-pinned assets to the product (or to the new default variant) and retire the bridge** — otherwise those images disappear. This is a hard prerequisite for deleting former-master rows in the rake task.+### Product creation flowToday: create product → `ensure_master` auto-builds a master variant with product-level price.@@ -339,11 +360,12 @@ If no `variants` are provided, one default variant is auto-created (simple produ## Open Questions-None at this time.+1. **Stock-aware default vs. sticky default.** The current computed `default_variant` is stock-aware: it returns the first _purchasable_ variant, so a product's displayed price/SKU follows stock. The FK approach makes the default _sticky_ — it only auto-promotes on delete/discontinue, **not on stock-out** — so the displayed default could point at an out-of-stock variant. Decide whether to (a) accept sticky behavior, or (b) extend the auto-promote rule to also re-point when the default goes out of stock (preserving today's behavior).## References- Industry standard: every product has at least one regular variant, no hidden "master". The variant is the purchasable unit.-- Current master variant implementation: `spree/core/app/models/spree/product.rb` (lines 93-107, 232-248, 305-331, 692-696)-- Current ghost callbacks: `spree/core/app/models/spree/variant.rb` (lines 618-678)+- Current master variant implementation: `spree/core/app/models/spree/product.rb` — master/variants associations ≈90-104, delegations ≈283-296, `has_variants?`/`default_variant`/`default_variant_id` ≈353-379, `master` paranoia override ≈577-579 (line numbers as of 2026-06-30)+- Current ghost callbacks: `spree/core/app/models/spree/variant.rb` ≈730-794 (`set_master_out_of_stock` ≈730, `remove_prices_from_master_variant` ≈788, `remove_stock_items_from_master_variant` ≈792)- Related plan: `6.0-cart-order-split.md` (LineItem still points to variant)+- Related plan: `5.5-6.0-product-media-system.md` (introduced the legacy master-pinned media bridge — see Edge Cases)diff --git a/spree/core/db/migrate/20260630000001_add_default_variant_id_to_spree_products.rb b/spree/core/db/migrate/20260630000001_add_default_variant_id_to_spree_products.rbnew file mode 100644index 0000000000..0cfe7f6361--- /dev/null+++ b/spree/core/db/migrate/20260630000001_add_default_variant_id_to_spree_products.rb@@ -0,0 +1,9 @@+class AddDefaultVariantIdToSpreeProducts < ActiveRecord::Migration[7.2]+ # Additive: the column is nullable and stays unused until the model cuts over+ # to the FK. Run +bundle exec rake spree:remove_master_variant+ afterwards to+ # backfill it.+ def change+ add_column :spree_products, :default_variant_id, :bigint+ add_index :spree_products, :default_variant_id+ end+enddiff --git a/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml b/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.ymlnew file mode 100644index 0000000000..6e9a01dadc--- /dev/null+++ b/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml@@ -0,0 +1,35 @@+# Spree 5.6 → 6.0 upgrade manifest.+#+# Lists ONLY the version-specific rake tasks that perform data backfills.+# Universal upgrade steps (bundle update, db:migrate, scheduling cron jobs,+# reviewing breaking changes) are NOT in this file:+#+# - `bundle update` + `db:migrate` are handled by your deploy pipeline+# (Heroku release phase, K8s init container, Render auto-migrate,+# Capistrano deploy hook, etc.) and by the @spree/cli's `spree upgrade`+# wrapper for local development.+# - Cron scheduling, optional tunings, and human-readable behavior changes+# live in the upgrade doc at docs/developer/upgrades/5.6-to-6.0.mdx.+#+# This manifest is the machine-runnable shape — what `bin/rake spree:upgrade`+# (in production) and `spree upgrade` (in dev) execute. Every step must be a+# rake task and must be idempotent. Re-running the full manifest is safe.+---+from: "5.6"+to: "6.0"+docs: "https://spreecommerce.org/docs/developer/upgrades/5.6-to-6.0"++steps:+ - id: remove_master_variant+ name: "Migrate products off the master variant"+ task: "spree:remove_master_variant"+ notes: |+ Backfills spree_products.default_variant_id and retires the hidden master+ variant: simple products' masters become regular variants, ghost masters+ on products with variants are deleted (or kept as regular variants when+ they still carry line items), and variant_count is recomputed to the real+ count. Until this runs, products have a NULL default_variant_id.++ Run spree:media:migrate_master_images_to_product_media first and let its+ jobs finish, so no master-pinned media is lost when ghost masters are+ deleted.diff --git a/spree/core/lib/tasks/remove_master_variant.rake b/spree/core/lib/tasks/remove_master_variant.rakenew file mode 100644index 0000000000..2dceec3915--- /dev/null+++ b/spree/core/lib/tasks/remove_master_variant.rake@@ -0,0 +1,55 @@+namespace :spree do+ desc <<~DESC+ Migrates products off the master variant. Idempotent (products that already+ have a default_variant_id are skipped) and loud about deletions.++ For each product:+ * With real variants: point default_variant_id at the first variant by+ position, then delete the now-empty master — unless it still carries+ line items, in which case keep it as a regular variant (is_master=false)+ so historical orders stay intact.+ * Simple (no-variant) products: convert the master into a regular variant+ (is_master=false) and point default_variant_id at it.+ * Recompute variant_count to the real variant count.++ Prerequisite: run +spree:media:migrate_master_images_to_product_media+ first+ so no master-pinned media is lost when ghost masters are deleted.+ DESC+ task remove_master_variant: :environment do+ migrated = converted = deleted = kept = 0++ # with_deleted: Product/Variant are paranoid, so soft-deleted rows would+ # otherwise be skipped and keep a NULL default_variant_id.+ Spree::Product.with_deleted.where(default_variant_id: nil).find_each do |product|+ master = Spree::Variant.where(product_id: product.id, is_master: true).first+ first_variant = Spree::Variant.where(product_id: product.id, is_master: false).order(:position).first++ if first_variant+ product.update_column(:default_variant_id, first_variant.id)++ if master && master.line_items.exists?+ master.update_column(:is_master, false)+ kept += 1+ elsif master+ Rails.logger.info("[remove_master_variant] deleting master variant #{master.id} of product #{product.id}")+ master.really_destroy!+ deleted += 1+ end+ elsif master+ master.update_column(:is_master, false)+ product.update_column(:default_variant_id, master.id)+ converted += 1+ else+ next+ end++ variant_count = Spree::Variant.where(product_id: product.id, deleted_at: nil).count+ product.update_column(:variant_count, variant_count) unless product.variant_count == variant_count++ migrated += 1+ end++ puts " Migrated #{migrated} product(s): converted #{converted} simple master(s), " \+ "deleted #{deleted} ghost master(s), kept #{kept} master(s) with order history."+ end+enddiff --git a/spree/core/spec/lib/tasks/remove_master_variant_spec.rb b/spree/core/spec/lib/tasks/remove_master_variant_spec.rbnew file mode 100644index 0000000000..1c7e3cbdc8--- /dev/null+++ b/spree/core/spec/lib/tasks/remove_master_variant_spec.rb@@ -0,0 +1,116 @@+require 'spec_helper'+require 'rake'++describe 'spree:remove_master_variant' do+ subject { Rake::Task[task_name] }++ let(:task_name) { 'spree:remove_master_variant' }++ before(:all) do+ Rake::Task.define_task(:environment)+ load Spree::Core::Engine.root.join('lib', 'tasks', 'remove_master_variant.rake')+ end++ before { subject.reenable }++ # Resolve the master by the is_master column — Product#master becomes a+ # deprecated alias for default_variant later, so the spec must not call it.+ def master_for(product)+ Spree::Variant.with_deleted.find_by(product_id: product.id, is_master: true)+ end++ # The computed Product#default_variant_id method shadows the attribute reader,+ # so read the raw column to assert on the persisted value.+ def persisted_default_variant_id(product)+ product.reload[:default_variant_id]+ end++ # Build the pre-migration shape — one is_master variant plus `extra` non-master+ # variants — without depending on what the factory's lone auto-variant happens+ # to be (a master today, a default variant after the factory is updated) or on+ # default_variant_id being unset.+ def legacy_product(extra: 0)+ product = create(:product)+ Spree::Variant.where(product_id: product.id).first.update_column(:is_master, true)+ product.update_column(:default_variant_id, nil)+ extra.times { create(:variant, product: product) }+ product+ end++ shared_examples 'an idempotent migration' do+ it 'leaves default_variant_id and variant_count unchanged on re-run' do+ subject.invoke+ default_variant_id = persisted_default_variant_id(product)+ variant_count = product.reload.variant_count++ subject.reenable+ subject.invoke++ expect(persisted_default_variant_id(product)).to eq(default_variant_id)+ expect(product.reload.variant_count).to eq(variant_count)+ end+ end++ context 'simple product (master only)' do+ let!(:product) { legacy_product }+ let!(:master_id) { master_for(product).id }++ it 'converts the master into a regular variant and points default_variant_id at it' do+ subject.invoke++ expect(Spree::Variant.find(master_id).is_master).to be(false)+ expect(persisted_default_variant_id(product)).to eq(master_id)+ expect(product.reload.variant_count).to eq(1)+ end++ it_behaves_like 'an idempotent migration'+ end++ context 'product with real variants and a ghost master' do+ let!(:product) { legacy_product(extra: 1) }+ let!(:master_id) { master_for(product).id }+ let!(:real_variant) { Spree::Variant.where(product_id: product.id, is_master: false).order(:position).first }++ it 'deletes the master and points default_variant_id at the first variant' do+ subject.invoke++ expect(Spree::Variant.with_deleted.exists?(master_id)).to be(false)+ expect(persisted_default_variant_id(product)).to eq(real_variant.id)+ expect(product.reload.variant_count).to eq(1)+ end++ it_behaves_like 'an idempotent migration'+ end++ context 'master that still carries line items' do+ let!(:product) { legacy_product(extra: 1) }+ let!(:master_id) { master_for(product).id }+ let!(:real_variant) { Spree::Variant.where(product_id: product.id, is_master: false).order(:position).first }++ # The master is a stripped ghost (the real variant cleared its stock), so a+ # current line item can't validate — model a historical order line instead.+ let!(:line_item) do+ order = create(:order)++ line_item = Spree::LineItem.new(+ order: order,+ variant: master_for(product),+ quantity: 1,+ price: 10,+ currency: order.currency+ )+ line_item.save!(validate: false)+ line_item+ end++ it 'keeps the master as a regular variant instead of deleting it' do+ subject.invoke++ expect(Spree::Variant.exists?(master_id)).to be(true)+ expect(Spree::Variant.find(master_id).is_master).to be(false)+ expect(persisted_default_variant_id(product)).to eq(real_variant.id)+ end++ it_behaves_like 'an idempotent migration'+ end+end