Skip to content

armgit / spree

Public Imported from GitHub
0

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.

20.7 KB
Raw Blame

Remove Master Variant

Status: Implemented (PR #14265, 2026-07-10) — Phases 1–4: is_master removed from all models, default_variant_id FK + ensure_default_variant/set_default_variant/auto_promote_default_variant wired on Product, and the spree:remove_master_variant data-migration rake task landed. Remaining: Phase 5 cleanup only — dropping the physical is_master column and the deprecated master/variants_including_master aliases (scoped to 6.1). Target: Spree 6.0 Depends on: None (standalone, but coordinate with Cart/Order split) Author: Damian + Claude Last updated: 2026-07-20

Summary

Eliminate the hidden "master" variant pattern. Every product will have at least one regular variant. Simple products (no options) have exactly one variant. Products with options have N variants. A default_variant_id FK on Product replaces the is_master flag as the way to identify the "face" of the product.

This removes the single most confusing Spree-specific pattern for new developers and eliminates an entire class of bugs caused by master/non-master branching.

Problem

Every Spree product has a hidden variant with is_master: true. This master variant:

  1. Stores price, SKU, weight for simple products — then gets stripped of prices and stock when real variants are created (via remove_prices_from_master_variant, remove_stock_items_from_master_variant callbacks). It becomes a ghost row.

  2. Forces two scopes everywhere. variants (excludes master, 99% of use cases) vs variants_including_master (includes master, needed for through-associations like prices, stock_items, line_items). Pick the wrong one and you either miss data or double-count.

  3. Creates has_variants? branching throughout the codebase. Every piece of code that touches pricing, stock, availability, or display must check if has_variants? ... else ... master .... This is the hallmark of a leaky abstraction.

  4. Confuses the delegation chain. product.price → default_variant → either master (no variants) or first purchasable variant (has variants). product.sku → master (always). Two different delegation targets on the same model.

  5. Breaks stock state. Master gets stock items on creation, they're deleted when real variants appear. Delete all variants → master has no stock items → broken state.

No other modern commerce platform uses this pattern. The industry standard is: every product has at least one regular variant, one of which is designated the default.

Blast radius

Pattern Occurrences Files
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)

  • Remove is_master column from spree_variants. All variants are peers.
  • Add default_variant_id FK on spree_products. Points to the variant used for price display, default add-to-cart, and property delegation. Required (not nullable) — every product must have a default variant.
  • Every product has at least one variant. Creating a product auto-creates one variant (like today's master, but without the special flag). Simple products have one variant with no option values. Products with options have N variants.
  • Option values on variants become truly optional. Today validates :option_value_variants, presence: true, unless: :is_master?. After: option values are optional on all variants. A simple product's sole variant just has no option values.
  • product.variants returns ALL variants (no is_master filter). Drop the variants_including_master scope entirely.
  • Delegation simplification. All product-level convenience methods (price, sku, weight, cost_price, etc.) delegate to default_variant. One delegation target, no branching.
  • API: master_variant expand renamed to default_variant. Deprecation alias for one release.
  • LineItem stays belongs_to :variant. This is correct. No change.
  • StockItem stays belongs_to :variant. This is correct. No change.
  • Add-to-cart stays variant-centric. POST /carts/:id/items { variant_id: "variant_xxx" }. No change.
  • Remove all ghost callbacks. remove_prices_from_master_variant, remove_stock_items_from_master_variant, set_master_out_of_stock — all deleted.

Design Details

Product model (after)

class Spree::Product < Spree.base_class
  # Single variants association — no is_master filter
  has_many :variants,
           -> { order(:position) },
           inverse_of: :product,
           class_name: 'Spree::Variant',
           dependent: :destroy

  # Default variant — the "face" of the product
  belongs_to :default_variant,
             class_name: 'Spree::Variant',
             optional: true  # nullable during creation, set in after_create

  has_many :prices, -> { order('spree_variants.position, spree_variants.id, currency') },
           through: :variants, source: :prices
  has_many :stock_items, through: :variants
  has_many :line_items, through: :variants
  has_many :orders, through: :line_items

  # All delegations go to default_variant — one target, no branching
  [
    :sku, :barcode, :weight, :height, :width, :depth, :dimensions_unit, :weight_unit,
    :price, :price_in, :amount_in, :compare_at_price, :compare_at_amount_in,
    :currency, :cost_currency, :cost_price, :track_inventory
  ].each do |method_name|
    delegate method_name, :"#{method_name}=", to: :default_variant
  end

  delegate :display_amount, :display_price, :has_default_price?, :track_inventory?,
           :display_compare_at_price, :images, to: :default_variant

  after_create :ensure_default_variant
  after_create :set_default_variant

  validates :default_variant, presence: true, on: :update

  # Renamed from has_variants? — "does this product have options to choose from?"
  def has_multiple_variants?
    return variants.size > 1 if variants.loaded?

    variant_count > 1
  end

  # Simple — always at least one variant
  def purchasable?
    variants.any?(&:purchasable?)
  end

  def in_stock?
    variants.any?(&:in_stock?)
  end

  def on_sale?(currency)
    prices.where(currency: currency).any?(&:discounted?)
  end

  # Auto-promote next variant when default is deleted/discontinued
  after_save :auto_promote_default_variant

  private

  def ensure_default_variant
    return if variants.any?

    variants.create!
  end

  def set_default_variant
    update_column(:default_variant_id, variants.first.id) if default_variant_id.nil?
  end

  def auto_promote_default_variant
    return if default_variant&.available?

    next_variant = variants.active.order(:position).first
    update_column(:default_variant_id, next_variant.id) if next_variant
  end
end

Variant model (after)

class Spree::Variant < Spree.base_class
  belongs_to :product, class_name: 'Spree::Product', touch: true

  # Option values are optional on ALL variants
  # Simple product's variant: no option values
  # Multi-variant product: each variant has option values
  has_many :option_value_variants, class_name: 'Spree::OptionValueVariant'
  has_many :option_values, through: :option_value_variants

  # No more is_master guards
  after_create :create_stock_items

  # Removed:
  # - validates :option_value_variants, presence: true, unless: :is_master?
  # - after_create :set_master_out_of_stock, unless: :is_master?
  # - after_commit :remove_prices_from_master_variant, unless: :is_master?
  # - after_commit :remove_stock_items_from_master_variant, unless: :is_master?
  # - is_master column and all references

  scope :eligible, -> { all }  # All variants are eligible (no master filtering needed)

  def exchange_name
    option_values.any? ? options_text : name
  end

  def descriptive_name
    option_values.any? ? "#{name} - #{options_text}" : name
  end
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.

# Product serializer — current (shipped) state
one :default_variant, resource: Spree.api.variant_serializer,
    if: proc { expand?('default_variant') }

Store API response — already returns default_variant_id, no master_variant:

{
  "id": "prod_86Rf07xd4z",
  "name": "Classic Tee",
  "default_variant_id": "variant_k5nR8xLq",
  "price": 29.99,
  "sku": "TSHIRT-001",
  "variants": [...]
}

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
  • StockItem belongs_to :variant — unchanged
  • Add-to-cart takes variant_id — unchanged
  • Prices belong to variants — unchanged
  • Nested attributes for variants on Product — unchanged (just remove the separate master nested attributes)

Migration Path

Phase 1: Add default_variant_id column

class AddDefaultVariantIdToProducts < ActiveRecord::Migration[7.2]
  def change
    add_column :spree_products, :default_variant_id, :bigint
    add_index :spree_products, :default_variant_id
  end
end

Phase 2: Data migration (rake task)

# rake spree:remove_master_variant
#
# For each product:
#
# Case 1: Product has real variants (variant_count > 0)
#   - Master variant has been stripped of prices/stock (ghost)
#   - Set default_variant_id to first non-master variant (by position)
#   - Delete the master variant (it has no prices, no stock, no line items)
#   - If master HAS line items (old completed orders), keep it but set is_master=false
#
# Case 2: Product has NO real variants (simple product)
#   - Master is the only variant, holds all data
#   - Set is_master = false (convert to regular variant)
#   - Set default_variant_id to this variant
#
# For all products:
#   - Update variant_count to reflect actual count (all variants, no master exclusion)

This task must be idempotent and reversible (soft — we can't re-create deleted masters, but we can log what was deleted).

Phase 3: Model changes

  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 (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 Variant
  8. Remove option_value_variants presence validation
  9. Update eligible scope (no is_master filter needed)
  10. Update factories: product factory creates one variant instead of master
  11. Update Product#sync_variant_state! (called by apply_variants to keep the create/update response fresh). Drop the @default_variant/@default_variant_id memo-clearing — default_variant becomes a belongs_to FK, so reset the association instead. The variant_count re-read (pick(:variant_count)) stays: the counter is still maintained by an out-of-band increment_counter callback, so the in-memory attribute is still stale after nested-variant mutation.
  12. Replace the save_master/master_updated?/@nested_changes/reset_nested_changes cluster with belongs_to :default_variant, autosave: true. On create, a variant built via the delegated setters is autosaved through the variants collection; on update, autosave: true persists the modified default variant (and cascades its validation) when the product is saved — this covers the delegated-write case (product.sku = …; save) that issue #5306 addressed, with no custom save hook. Plain belongs_to alone doesn't do this: it autosaves only new associated records, not modified existing ones. The @nested_changes touch-dirty flag is dropped — Variant belongs_to :product, touch: true covers touch propagation.
  13. Remove the deprecated option_values_hash variant-building cluster — build_variants_from_option_values_hash, its after_create callback, ensure_option_types_exist_for_values_hash, attr_accessor :option_values_hash, and :option_values_hash from Spree::PermittedAttributes. It already carried a "removed in 6.0" warning and is used nowhere but its own specs; removing it also avoids a phantom optionless variant that arose only when product-level sku/price (which eagerly build the default variant) were combined with that hash flow.

Phase 4: API + serializer updates

  • Rename master_variant expand to default_variant (alias old name)
  • Update admin serializer (cost_price, cost_currency from default_variant instead of master)
  • Update SDK types via typelizer pipeline

Phase 5: Cleanup (6.1)

  • Remove is_master column migration
  • 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

Completed orders referencing master variant

LineItems in completed orders may reference the old master variant. Two options:

  • (a) Keep master variants that have line items — set is_master = false, they become regular variants. Old orders still work. This is the safe path.
  • (b) Migrate line items to point to the default variant. Risky — changes historical data.

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 flow

Today: create product → ensure_master auto-builds a master variant with product-level price.

After: create product with variants nested attributes → first variant becomes default_variant. If no variants provided, one empty variant is auto-created (simple product). Price is set per-variant, not on the product.

Nested attributes

Today: accepts_nested_attributes_for :master allows setting master's properties inline.

After: accepts_nested_attributes_for :variants handles everything. No separate master nested attributes. Admin API accepts variants: [{ sku: ..., prices: [...] }].

Price delegation

Today: product.price → default_variant (which may be master or first purchasable variant, with branching).

After: product.price → default_variant.price (always the same record, no branching). Product has no price column — it's purely a delegation convenience. If the merchant wants to change which variant is "default", they update default_variant_id.

Constraints on Current Work

  • Stop adding is_master? guards. New code should not branch on master/non-master.
  • Use variants_including_master for through-associations (prices, stock_items, line_items) — these will become just variants after migration.
  • Don't add new delegations to master. New delegations should go through default_variant.
  • New variant callbacks should not use unless: :is_master?. They should apply to all variants equally.
  • variant_count staleness is structural, not master-specific. It's maintained by an out-of-band counter increment_counter callback, so the in-memory attribute goes stale whenever variants are mutated within a request (e.g. apply_variants during create/update). Product#sync_variant_state! re-reads it so the serialized response stays fresh; this stays necessary after master removal. Don't assume removing master removes the need to re-sync.

Resolved Questions

  1. default_variant_id management. Auto-promote the next variant (by position) when the current default is deleted or discontinued. No admin action required.

  2. Variant count semantics. Rename has_variants? to has_multiple_variants? — returns variant_count > 1. Clearer intent: "does this product have more than one variant (i.e., options to choose from)?"

  3. Product creation API. No product-level price param. Price lives on variants. The Admin API accepts variants as nested attributes:

# POST /api/v3/admin/products
{
  name: "T-Shirt",
  shipping_category_id: "sc_abc",
  status: "draft",
  variants: [
    {
      sku: "TSHIRT-S",
      options: [{ name: "size", value: "Small" }],
      prices: [
        { currency: "USD", amount: 29.99 },
        { currency: "EUR", amount: 27.99 }
      ],
      stock_items: [
        { location_id: "loc_abc", quantity: 10, backorderable: true }
      ]
    }
  ]
}

If no variants are provided, one default variant is auto-created (simple product). Price must then be set on that variant via a follow-up call or via a top-level price convenience param that forwards to the auto-created variant.

  1. Weight/dimensions stay on Variant. The variant is the purchasable/shippable unit. A Small and XL t-shirt weigh differently. product.weight delegates to default_variant.weight as a convenience — no product-level columns.

Open Questions

  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 — 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)