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.
Replace Taxons with Categories & Add Collections
Status: Implemented (PR #14302, 2026-07-19). The Category read/write surface landed earlier (5.5–5.6); PR #14302 completed the 6.0 core: the spree_taxons → spree_categories table rename + inheritance flip (Spree::Category < Spree.base_class, Spree::Taxon retained as a deprecation alias), the full Collection stack (model + join + rules + DB/Meilisearch manual sort + API), the taxon→category/collection data-migration task, and de-ruling Category. Remaining (all 6.1): the channel-aware reimplementation of CollectionRules::AvailableOn — Phase 5, which ships now with an interim legacy-available_on apply and rides with 6.0-channels-catalogs-b2b.md; and dropping spree_taxon_rules + Spree::TaxonRule/TaxonRules::* + the Taxonomy model and table (Phase 6). Taxonomy became data-only in 6.0 — Phase 5b removed every runtime path that created, touched or validated one, leaving only the upgrade task's reader and the pre-upgrade store-resolution fallbacks. Nothing 6.0-blocking is left.
Target: Spree 6.0 (Category surface landed in 5.5–5.6; 6.0 renames the table, splits out Collection, and drops Taxonomy)
Depends on: API v3 conventions, ProductType plan (6.0-product-types.md), Rich Text Descriptions plan (6.0-rich-text-descriptions.md), Admin SPA plan (6.0-admin-spa.md — dashboard UI), Channels/Publications plan (6.0-channels-catalogs-b2b.md — the CollectionRules::AvailableOn rule's channel-aware implementation depends on its available_on → ProductPublication#published_at migration; see Migration Phase 5)
Author: Damian + Claude
Last updated: 2026-07-28
Summary
Split the overloaded Taxon model into two distinct concepts that every modern commerce platform separates:
- Category — hierarchical product classification (Men > Clothing > T-Shirts). A product's primary organizational home. Manual membership only.
- Collection — flat, curated or rule-based product groupings ("Summer Sale", "New Arrivals", "Best Sellers"). Supports both manual curation and automatic rules.
Drop the Taxonomy model entirely — it's a grouping layer that adds indirection without value. Categories become a single tree per store (rooted, nested set). Collections are flat, store-scoped, and own the current automatic/rule-based functionality.
This also renames Classification to ProductCategory and TaxonRule to CollectionRule.
Problem
"Taxon" and "Taxonomy" are jargon. No other commerce platform uses these terms. Every new developer has to learn what they mean. The industry-standard separation is Category (hierarchical) + Collection (flat/curated).
Taxon is overloaded. The same model serves as both hierarchical categories AND flat collections (via the "Collections" taxonomy with automatic rules). These have fundamentally different semantics:
- Categories are hierarchical, manual, and define a product's primary classification
- Collections are flat, often automatic (rule-based), and used for merchandising (seasonal campaigns, "on sale", "new arrivals")
Taxonomy adds indirection without value.
Taxonomyis essentially a named container for a tree of Taxons, scoped to a Store. The root Taxon mirrors the Taxonomy name (kept in sync via callbacks). In practice, merchants have 2-3 taxonomies ("Categories", "Brands", "Collections"). This grouping is replaced by separating Collections out entirely; brands are out of scope (see Key Decisions → Brands).Classificationtells you nothing. The Product↔Taxon join model name gives no hint about what it joins.
Current State
Much of the Category half has already shipped (5.5–5.6). What exists today:
| Model | API name | Prefix | Notes |
|---|---|---|---|
Spree::Taxonomy |
n/a (internal) | txnmy_ |
Container for taxon trees, scoped to store. Being dropped. |
Spree::Taxon |
categories |
ctg_ |
Nested set tree on spree_taxons; still carries automatic + TaxonRule (Collection's future home) |
Spree::Category |
categories |
ctg_ |
class Category < Taxon with default_scope { manual } + requires_taxonomy? = false. Not STI — there is no type column; it shares spree_taxons rows with Taxon and is a scoped view whose ownership is driven by store_id instead of taxonomy_id. |
Spree::Classification |
n/a | n/a | Product↔Taxon join (table: spree_products_taxons) |
Spree::TaxonRule |
n/a | txrule_ |
STI: AvailableOn, Sale, Tag |
Already shipped:
store_idonspree_taxons(nullable) + backfill taskspree:taxons:backfill_store_id;Spree::Categoryowns viastore_iddirectly (no taxonomy required, throughSingleStoreResource/ensure_store).- Counter caches on
spree_taxons:children_count,classification_count(direct), andproducts_count(descendant-inclusive, deduped — recomputed, not a Rails counter_cache). - Store API: read-only
categoriescontroller +CategorySerializer(product exposestaxonsunder thecategorieskey, expand-gated). - Admin API: full CRUD
categoriescontroller +reposition+ nestedproducts/custom_fields/translations;Admin::CategorySerializer < CategorySerializer. - Promotion rules already speak
categoryon the wire (Promotion::Rules::Taxon#api_type => 'category', permitscategory_ids); the model rename is still pending.
No longer true: default taxonomies ("Categories", "Brands", "Collections") and automatic taxons ("On Sale", "New Arrivals") are no longer auto-created per store — Store#ensure_default_taxonomies_are_created / ensure_default_automatic_taxons were deprecated (2026-03-10) and removed in 5.5 (PR #14020, 2026-05-11). New stores get no taxonomies; categories are created on demand. The taxonomy_*_name locale keys remain (only brand_taxon still reads taxonomy_brands_name).
"Manual" (position) sort in the v3 Store API — implemented for both providers. "Manual" sort orders products by their hand-set position within the grouping (ProductCategory.position / ProductCollection.position). The DB provider infers the grouping from the applied in_category/in_collection filter, defaults a grouping page's blank sort to manual, and orders by ProductCollection.position (flat, for collections) or MIN(ProductCategory.position) collapsed per product (subtree, for categories) — reusing the join the filter already made. The Meilisearch provider reaches the same result natively via single index + distinct: ProductPresenter emits per-grouping membership docs (shared scalar grouping_id + position), a manual grouping page filters grouping_id and sorts position:asc, and distinctAttribute = product_id collapses the duplicates on non-grouping queries (facet counts/totals accurate on MS ≥ 1.40). See Open Questions (resolved).
Remaining for 6.0
The Category read/write surface is done. What's left:
- Table rename —
spree_taxons→spree_categories,spree_products_taxons→spree_product_categories(+ FK columns), plus the inheritance flip (Category becomes the base class,Taxonbecomes a deprecation alias).spree_taxon_rulesis dropped (not renamed) —spree_collection_rulesis a new table. - The full
Collectionstack —Spree::Collection,Spree::ProductCollectionjoin,Spree::CollectionRule(STI), and the Store + Admin API. Nothing exists yet. (Dashboard UI is tracked in6.0-admin-spa.md.) - Model-level split — move
automatic,rules_match_policy,sort_order, andtaxon_rulesoff Category onto Collection (today they still live onTaxon/Categoryand are only excluded at the API layer). - Drop
Taxonomy— remove the model, table, and thetaxonomy_idcolumn (6.1). The brand methodsProduct#brand_taxon/#brand_name(the only remainingTaxonomy-dependent runtime path) are removed in 6.0 (Phase 3); brands are out of scope with no replacement (see Key Decisions → Brands).
Key Decisions (do not deviate without discussion)
Category
Spree::Taxonrenamed toSpree::Category,spree_taxonsrenamed tospree_categoriesSpree::Taxonomydropped. Categories are a single nested set per store. Thetaxonomy_idcolumn becomesstore_iddirectly on the category.Spree::Classificationrenamed toSpree::ProductCategory, tablespree_products_taxonsrenamed tospree_product_categories, columnstaxon_id→category_id- Categories are manual only. The
automaticflag,rules_match_policy,sort_order, andtaxon_rulesassociation move to Collection. - Prefix stays
ctg_(already in use) - Nested set stays.
awesome_nested_setwithparent_id,lft,rgt,depth,children_count. Proven, no reason to change. pretty_nameand hierarchicalpermalinkstay. These are valuable for breadcrumbs and SEO.hide_from_navis removed (reversal, 2026-08-05 — it previously "stayed"). Nothing ever read it: no serializer exposed it, no scope or query filtered on it, and no storefront or dashboard consumed it, so it was a write-only flag an API client could set to no effect. The Ruby surface (validation, Ransack entry, permitted attributes, admin param) and the SDK params are gone; the column drops in 6.1 with the other dead columns. Collections never had it — the column in this plan's Phase 1 migration was specified but never implemented, and is not being added.
Counter caches
Two product-count concepts, named consistently across grouping models. products_count means "products in this grouping, including descendants" — for a flat Collection that's just its direct members, so the name means the same thing on both models.
| Model | Column | Meaning | Maintained by |
|---|---|---|---|
| Category | products_count |
descendant-inclusive, deduped (self + subtree) | recompute (recalculate_products_count) |
| Collection | products_count |
direct (flat) | Rails counter_cache on ProductCollection |
| Product | categories_count |
# categories the product is in | Rails counter_cache on ProductCategory |
| Product | collections_count |
# collections the product is in | Rails counter_cache on ProductCollection |
- Drop
classification_counton bothspree_categories(only the legacy Rails admin reads it; the dashboard/API useproducts_count) andspree_products(renamed tocategories_count). - The category's
products_countis not a Rails counter_cache — it's recomputed on classification change / node move, soProductCategorycarries no category-side count counter.
Collection
- New model
Spree::Collection— flat (no tree), store-scoped - New join table
Spree::ProductCollection(replaces the automatic taxon's use of Classification) - Owns automatic/rule-based membership — the
automaticflag,rules_match_policy, and rules association move here from Taxon Spree::TaxonRulerenamed toSpree::CollectionRule— STI subtypesTag,Sale,AvailableOn, all registered inconfig.spree.collection_rules(which mirrors the existingconfig.spree.taxon_rules).AvailableOnships with an interim legacy-column implementation; its channel-aware behavior depends on6.0-channels-catalogs-b2b.md(see Design Details → Automatic collection regeneration; Migration Phase 5)- Prefix:
coll_ - Both manual and automatic collections. Manual collections have
ProductCollectionrecords managed by admins. Automatic collections haveCollectionRulerecords that regenerate membership. - Sort order on Collection, not Category. The
SORT_ORDERSconstant (manual,best_selling,price asc, etc.) moves to Collection.
Taxonomy → dropped
- No replacement model, and no
kindcolumn. Taxonomy simply goes away. With brands out of scope (see below), there's no remaining need to distinguish "kinds" of trees — a store has one category tree plus flat collections. - Store scoping moves to Category directly. Every category has
store_id(required). Children auto-copy from parent on create. Simplewhere(store_id:)scoping, no joins needed.
Brands → out of scope (no brand feature in 6.0)
Decision: Spree 6.0 ships no brand-specific construct — no Spree::Brand model, no brand attribute/column, no :brands tag context, no category kind column. The going-forward model is just Category (hierarchy) + Collection (curated/rule-based); a store that wants to group products by brand models it as a regular Category or Collection like any other grouping.
- The existing
Product#brand_taxon/#brand_nameand the "Brands" taxonomy convention are removed with no replacement. The brand methods go in 6.0 (Phase 3) — they were the only remainingTaxonomy-dependent runtime path, so removing them is what unblocks droppingTaxonomyitself (model/table) in 6.1. - The
taxonomy_brands_namelocale key is removed. - Rationale: none of the surveyed platforms model brand as a category, and a proper first-class brand is a larger feature than 6.0 warrants. Rather than ship a half-measure (brand-as-category or brand-as-tag), 6.0 ships nothing brand-specific — a dedicated
Spree::Brandcan be designed later (core or extension) without a rushed decision here.
Design Details
Category model
class Spree::Category < Spree.base_class
has_prefix_id :ctg
include Spree::TranslatableResource
include Spree::TranslatableResourceSlug
include Spree::Metafields
include Spree::Metadata
include Spree::MemoizedData
acts_as_nested_set dependent: :destroy, counter_cache: :children_count
# Store ownership via the shared concern — provides belongs_to :store, presence,
# and ensure_store (children inherit the parent's store). Replaces the old
# hand-rolled copy_store_from_parent; Taxon#set_store is deprecated for 6.0.
include Spree::SingleStoreResource
# Products
has_many :product_categories, class_name: 'Spree::ProductCategory', dependent: :destroy_async
has_many :products, through: :product_categories
# ProductType integration (from 6.0-product-types.md)
has_many :product_type_categories, class_name: 'Spree::ProductTypeCategory', dependent: :destroy
has_many :product_types, through: :product_type_categories
# Promotions
has_many :promotion_rule_categories, class_name: 'Spree::PromotionRuleCategory', dependent: :destroy
has_many :promotion_rules, through: :promotion_rule_categories
# Attachments
has_one_attached :image
has_one_attached :square_image
# Validations
validates :name, presence: true, uniqueness: { scope: %i[parent_id store_id], case_sensitive: false }
# Translations
TRANSLATABLE_FIELDS = %i[name pretty_name description permalink].freeze
translates(*TRANSLATABLE_FIELDS, column_fallback: !Spree.always_use_translations?)
# description rides the table backend above — NOT action_text. The old
# `translates :description, backend: :action_text` line is removed by
# 6.0-rich-text-descriptions.md Phase 3, which runs BEFORE this plan's
# table rename (its rake task is table-name-agnostic either way).
# Scopes
scope :for_store, ->(store) { where(store_id: store.id) }
# No automatic/rules — that's Collection's job
end
Interim state: today
Spree::Category < Spree::Taxon(sharesspree_taxons, notypecolumn). The rename flips this — Category becomes the base class onspree_categoriesandSpree::Taxonbecomes a deprecation alias (see Migration Phase 3). The design above is the post-rename target.
Collection model
class Spree::Collection < Spree.base_class
has_prefix_id :coll
include Spree::SingleStoreResource
include Spree::TranslatableResource
include Spree::TranslatableResourceSlug
include Spree::Metafields
include Spree::Metadata
# FriendlyId with history, mirroring Category/Taxon. `use: :history` records superseded
# permalinks in the shared `friendly_id_slugs` table (polymorphic, scoped by sluggable_type)
# so old collection URLs keep resolving after a RENAME — a deliberate SEO requirement.
# No new table (friendly_id_slugs already exists for Taxon). Within-store uniqueness is
# enforced separately by `validates :permalink, uniqueness: { scope: :store_id }` + the DB
# index: a collision ERRORS (exactly as Taxon does — friendly_id is not scoped and does not
# auto-suffix here). Generation mirrors Taxon's dual set_permalink — a model-level
# `before_validation` (so the column_fallback base column is populated for the default
# locale, which the Translation `before_save` alone misses) plus a Translation-level
# `before_save` — but flat: `generate_slug` is `name.to_url` with no parent prefix.
extend FriendlyId
friendly_id :permalink, slug_column: :permalink, use: :history
before_validation :set_permalink, if: :name
RULES_MATCH_POLICIES = %w[all any].freeze
# Space format — required by the sort pipeline (FiltersAggregator splits on a space).
# Owned by Collection (Category is manual-only and no longer defines SORT_ORDERS).
# pipeline: FiltersAggregator#to_api_sort splits on a space ('price asc' -> 'price'),
# and apply_sort maps to 'price'/'-price'/'best_selling'. Underscores would break default_sort.
SORT_ORDERS = [
'manual', 'best_selling',
'price asc', 'price desc',
'available_on desc', 'available_on asc',
'name asc', 'name desc'
].freeze
acts_as_list scope: :store_id
# store ownership (belongs_to :store + presence) comes from SingleStoreResource
# Products
has_many :product_collections, class_name: 'Spree::ProductCollection', dependent: :destroy_async
has_many :products, through: :product_collections
# Automatic rules. The association is named `rules` (not `collection_rules`) so the
# Admin API's write key equals the serializer's read key: ParamsNormalizer derives the
# flat nested-attributes key from the association name (`rules` → `rules_attributes`),
# so a `rules: [...]` payload routes correctly (read/write symmetry — see CLAUDE.md).
has_many :rules, class_name: 'Spree::CollectionRule', dependent: :destroy
accepts_nested_attributes_for :rules, allow_destroy: true,
reject_if: proc { |attrs| attrs['value'].blank? }
# Attachments
has_one_attached :image
has_one_attached :square_image
# Validations (store presence comes from SingleStoreResource)
validates :name, presence: true
validates :permalink, uniqueness: { scope: :store_id, case_sensitive: false, allow_blank: true }
validates :rules_match_policy, inclusion: { in: RULES_MATCH_POLICIES }, presence: true
validates :sort_order, inclusion: { in: SORT_ORDERS }, presence: true
# Translations
TRANSLATABLE_FIELDS = %i[name description permalink].freeze
translates(*TRANSLATABLE_FIELDS, column_fallback: !Spree.always_use_translations?)
# Interim: mirror the current Category — description via ActionText. This overrides the
# "text column per 6.0-rich-text-descriptions.md" target for the initial build (those
# primitives aren't shipped yet); that plan migrates BOTH Category and Collection off
# ActionText together.
translates :description, backend: :action_text
scope :manual, -> { where.not(automatic: true) }
scope :automatic, -> { where(automatic: true) }
# Regenerate product membership from rules (moved from Taxon)
def regenerate_products
return unless automatic?
Spree::Collections::RegenerateProducts.call(collection: self)
end
def products_matching_rules(opts = {})
return Spree::Product.none unless automatic? && rules.any?
# Same logic as current Taxon#products_matching_rules
end
end
Join tables
# Renamed from Spree::Classification
class Spree::ProductCategory < Spree.base_class
self.table_name = 'spree_product_categories'
acts_as_list scope: :category
# Product side is a Rails counter_cache (categories_count). Category side has
# NO counter_cache — its products_count is descendant-inclusive and recomputed.
belongs_to :product, class_name: 'Spree::Product', counter_cache: :categories_count, touch: true
belongs_to :category, class_name: 'Spree::Category', touch: true
validates :category, :product, presence: true
validates :category_id, uniqueness: { scope: :product_id }
end
# New
class Spree::ProductCollection < Spree.base_class
self.table_name = 'spree_product_collections'
acts_as_list scope: :collection
belongs_to :product, class_name: 'Spree::Product', counter_cache: :collections_count, touch: true
belongs_to :collection, class_name: 'Spree::Collection', counter_cache: :products_count, touch: true
validates :collection, :product, presence: true
validates :collection_id, uniqueness: { scope: :product_id }
end
CollectionRule (renamed from TaxonRule)
class Spree::CollectionRule < Spree.base_class
has_prefix_id :crule
MATCH_POLICIES = %w[is_equal_to is_not_equal_to contains does_not_contain].freeze
belongs_to :collection, class_name: 'Spree::Collection', inverse_of: :rules, touch: true
validates :collection, :type, :value, presence: true
validates :match_policy, inclusion: { in: MATCH_POLICIES }, presence: true
after_commit :regenerate_collection_products,
if: -> { saved_change_to_value? || destroyed? || saved_change_to_match_policy? }
end
# STI subtypes (all registered in config.spree.collection_rules, which mirrors config.spree.taxon_rules):
# Spree::CollectionRules::Tag — products with matching tags
# Spree::CollectionRules::Sale — products currently on sale
# Spree::CollectionRules::AvailableOn — products created/available within N days.
# Ships with the interim legacy-column `apply`; channel-aware reimplementation
# (against ProductPublication#published_at) is Migration Phase 5.
Automatic collection regeneration
Automatic membership is materialized into ProductCollection rows (as today's Classification is for automatic taxons). It regenerates on events — a CollectionRule change, a rules_match_policy change, or a product save (via AutoMatchCollections). Event-driven regeneration has no clock, so time-relative rules drift: a product that ages past an AvailableOn window stays in the collection until some unrelated write re-triggers evaluation.
A scheduled job closes that gap for time-based rules:
- Registry —
config.spree.time_based_collection_rules = [Spree::CollectionRules::AvailableOn]inengine.rb, net-new (notaxon_rulesequivalent — taxons ship no scheduled refresh, hence their drift). This is a separate axis from theconfig.spree.collection_rulesrule registry (which mirrorsconfig.spree.taxon_rules); apps/plugins append their own. - Job —
Spree::Collections::RegenerateTimeBasedJob < Spree::BaseJob(queue_as Spree.queues.collections): selects automatic collections that have a rule whosetypeis registered as time-based and callsSpree::Collections::RegenerateProductson each. - Cadence — not hardcoded in the gem; wired by the host app's scheduler (sidekiq-cron / solid_queue recurring), the same pattern as
Spree::StockReservations::ExpireJob. Hourly/daily is enough (AvailableOnwindows are day-granular).
AvailableOnships fully now, but its implementation is interim. The STI class ships in Phase 1 (registered incollection_rulesalongsideTag/Sale) so the Phase 4 rake migratesTaxonRules::AvailableOn→CollectionRules::AvailableOn1:1 (value + match_policy preserved) rather than dropping the data. Itsapplyis the same legacyspree_products.available_onquery the taxon rule already runs — a faithful, zero-behavior-change carry-over (the taxon rule was equally channel-unaware), which keeps migrated automatic collections computing correct membership and lets the scheduled job above refresh them. One caveat holds until the reimplementation (Migration Phase 5):
- Channel-unaware + on a doomed column. The
available_oncolumn is superseded by the channel-scopedProductPublication#published_atand is removed by6.0-channels-catalogs-b2b.md(its Phase 3 — "6.0 cleanup"). SoAvailableOnis a new reader of a column another 6.0 plan drops. Migration Phase 5 reimplementsapplyagainstpublished_atand — as a hard cross-plan ordering constraint — must land before the channels plan drops the column.
Product changes
Already shipped: has_many :categories, through: :classifications and a category_ids= setter that maps the API name to the underlying taxon_ids (accepting prefixed IDs, scoped to the product's store); main_taxon still exists. Still to add: primary_category, the collections association, and the collections_count counter. To remove: brand_taxon / brand_name (brands out of scope — see Key Decisions → Brands).
class Spree::Product < Spree.base_class
# Categories (renamed from taxons/classifications). `manual`-scoped during the
# transition — automatic categories are migrated to Collections in Phase 4, after
# which the scope is a no-op; it (and `taxons`) are dropped in 6.1.
has_many :product_categories, dependent: :delete_all, inverse_of: :product
has_many :categories, -> { manual }, through: :product_categories, source: :category
# Deprecation period (removed in 6.1). `taxons` stays a *real* association (not an
# alias_method) because it is Ransack-whitelisted (`taxons_id_in`) and Ransack
# needs a reflectable association; it lists every category via the join.
# `classifications` is a plain method alias (it is not Ransack-whitelisted).
has_many :taxons, through: :product_categories, source: :category, before_remove: :remove_category
alias_method :classifications, :product_categories
# Collections (new)
has_many :product_collections, dependent: :delete_all, inverse_of: :product
has_many :collections, through: :product_collections
# main_taxon → primary_category
def primary_category
@primary_category ||= categories.first
end
# brand_taxon / brand_name are REMOVED — no replacement. Brands are out of scope
# for 6.0 (see Key Decisions → Brands); group by brand via a Category or Collection.
end
Store changes
class Spree::Store < Spree.base_class
# Drop: has_many :taxonomies
# Drop: has_many :taxons, through: :taxonomies
has_many :categories, class_name: 'Spree::Category'
has_many :root_categories, -> { roots }, class_name: 'Spree::Category'
has_many :collections, class_name: 'Spree::Collection'
end
API
Store API already uses categories naming. Changes:
# Categories — SHIPPED (read-only in Store API)
GET /api/v3/store/categories # was taxons
GET /api/v3/store/categories/:id
GET /api/v3/store/products/:id?expand=categories
# Collections — PENDING (6.0)
GET /api/v3/store/collections
GET /api/v3/store/collections/:id
GET /api/v3/store/collections/:id/products # dedicated PLP (in_collection filter) — see note below
GET /api/v3/store/products/filters?collection_id=coll_… # facets/sort metadata (existing endpoint + new param)
# Admin API — categories SHIPPED (5.6)
GET /api/v3/admin/categories
POST /api/v3/admin/categories
PATCH /api/v3/admin/categories/:id
DELETE /api/v3/admin/categories/:id
PATCH /api/v3/admin/categories/:id/reposition
GET /api/v3/admin/categories/:id/products
POST /api/v3/admin/categories/:id/products
DELETE /api/v3/admin/categories/:id/products/:product_id
PATCH /api/v3/admin/categories/:id/products/:product_id/reposition
# (+ nested custom_fields and translations via concerns)
# Admin API — collections PENDING (6.0)
GET /api/v3/admin/collections
POST /api/v3/admin/collections
PATCH /api/v3/admin/collections/:id # reorder via `position` (acts_as_list reorders on save) — no separate reposition action
DELETE /api/v3/admin/collections/:id
GET /api/v3/admin/collections/:id/products
POST /api/v3/admin/collections/:id/products
DELETE /api/v3/admin/collections/:id/products/:product_id
PATCH /api/v3/admin/collections/:id/products/:product_id/reposition
# (+ nested custom_fields and translations via concerns)
#
# Bulk product membership (mirrors the category bulk endpoints):
POST /api/v3/admin/products/bulk_add_to_collections # { ids: [...], collection_ids: [...] }
POST /api/v3/admin/products/bulk_remove_from_collections # { ids: [...], collection_ids: [...] }
Unlike categories (a nested set that needs an explicit reposition with a target parent + index), collections are a flat acts_as_list, so the collection's own order is reordered by sending position on PATCH /collections/:id — matching the SPA <ResourceTable reorder> convention and the sibling flat resource (payment_methods). Only the nested membership (ProductCollection.position) keeps a dedicated reposition. Admin collection endpoints require the new read_collections / write_collections API-key scopes (JWT admins use CanCanCan as usual). Membership is deliberately not gated behind write_collections: collection_ids on a product write and the /products/bulk_*_collections endpoints are reachable with write_products, because filing a product into its groupings is part of maintaining the product — the same rule category_ids has always followed. Creating or configuring a collection (its rules, sort order, name) still requires write_collections.
Nested rules are written through a model-level sync setter (Spree::Collection#rules=), mirroring Spree::OptionType#option_values=: the client sends the full desired rule set under rules (prefixed crule_ ids update, id-less entries create, omitted rules are destroyed), decoded and applied in the parent's save transaction. normalize_params is deliberately not called on this controller so rules reaches the setter rather than being rewritten to rules_attributes.
Collection response (Admin — the Store serializer omits the merchandising config automatic, rules_match_policy, and rules; that's back-office state, not customer-facing). rules is expand-gated (?expand=rules), like custom_fields: a listing would otherwise serialize every collection's full rule set for callers that only need the basics, and the only consumer that needs them is the edit form. The shape below is the expanded one:
{
"id": "coll_k5nR8xLq",
"name": "Summer Sale",
"automatic": true,
"sort_order": "best_selling",
"rules_match_policy": "all",
"rules": [
{ "id": "crule_abc", "type": "Spree::CollectionRules::Tag", "value": "summer", "match_policy": "contains" }
],
"image_url": "https://...",
"products_count": 42,
"slug": "summer-sale"
}
The Store response is the customer-facing subset — id, name, slug/permalink, description/description_html, image_url/square_image_url, sort_order, position, meta_*, products_count (+ custom_fields on expand) — with no automatic/rules_match_policy/rules (internal merchandising state stays out of the Store API, per the store-vs-admin serializer rule).
Collection product listing (Store API)
Products in a collection are served by a dedicated endpoint, not a filter on /products. This follows the Shopify Storefront GraphQL model (collection { products }) where the collection is the path context and filters/sort layer on top. (Most REST APIs — WooCommerce, Medusa, commercetools, BigCommerce — use a ?collection_id= filter instead; we deliberately choose the nested style for cleaner requests and to apply the collection's own default sort automatically. in_collection is still kept as a Ransack scope for composite queries.)
GET /api/v3/store/collections/:id/products— a thin controller that resolves the collection and delegates to the same search-provider flow as/products(query, Ransack filters, pagination, serializer).def scopestays the base visibility scope (available+accessible_by) — it is not pre-scoped to the collection. Instead the controller injectsin_collection: collection.prefixed_idinto the filters, and each provider applies it: the DB provider via thein_collectionRansack scope, Meilisearch via thecollection_idsfilter. Collection scoping has to be a provider filter (not an AR pre-scope) because Meilisearch does its own filtering/counting/pagination and treats the AR scope only as a post-search visibility guard. No logic duplication.- Sort precedence. Effective sort = the request's
sortparam if present, otherwise the collection'ssort_order. Position ordering (ProductCollection.position) applies only when the effective sort ismanual; any dynamic sort — whether from the collection's own default or a shopper override — dismisses it. Because the listing runs through the provider (for thein_collectionfilter, pagination, and faceting), manual sort is implemented in the provider, not by bypassing it with a direct AR query. Both providers implement it — the DB provider orders byProductCollection.position; the Meilisearch provider queries per-grouping membership docs (single index +distinct) sorted byposition:asc. All dynamic sorts work on both. - Facets/sort metadata reuse the existing
GET /api/v3/store/products/filterswith a newcollection_idparam (parallel tocategory_id): it resolves the collection, scopesin_collection, and passes only the collection'ssort_ordertoFiltersAggregator— via asort_order:string param, not theCollectionobject (the aggregator stays decoupled from the model). No child facet (collections are flat). - Model:
Spree::Product.in_collectionscope (flat join tospree_product_collections, no descendants), whitelisted as a ransackable scope. (Noin_collectionsplural — the collection surface is single-collection; add it only if a real multi-collection filter appears.) - Meilisearch: index
collection_ids(flat, no ancestors) on the product document, add it tofilterable_attributes/facet_attributes, and handlein_collectioninbuild_filter_condition. Kept fresh byRegenerateProducts(touches products +enqueue_search_index).
Membership is materialized in ProductCollection for both manual and automatic collections, so read-time is always a plain join filter — rules are never evaluated per request.
Migration Path
Phase 1: Collection stack — schema + models (additive, no renames)
New tables first (so the models are testable in RSpec), then the models/code built on them. This ships alongside the untouched Taxon/automatic-taxon setup — nothing is renamed yet.
1a. Schema (new tables, additive):
class CreateSpreeCollections < ActiveRecord::Migration[7.2]
def change
create_table :spree_collections do |t|
t.string :name, null: false
t.text :description
t.string :permalink
t.boolean :automatic, null: false, default: false
t.string :rules_match_policy, null: false, default: 'all'
t.string :sort_order, null: false, default: 'manual'
t.integer :position
t.integer :products_count, null: false, default: 0
t.references :store, null: false
t.string :meta_title
t.string :meta_description
t.string :meta_keywords
t.jsonb :public_metadata
t.jsonb :private_metadata
t.timestamps
end
add_index :spree_collections, [:store_id, :permalink], unique: true
create_table :spree_product_collections do |t|
t.references :product, null: false
t.references :collection, null: false
t.integer :position
t.timestamps
end
add_index :spree_product_collections, [:collection_id, :product_id], unique: true
# NEW table — NOT a rename of spree_taxon_rules (kept data-only for the Phase 4
# migration, dropped in 6.1). STI type: Spree::CollectionRules::{Tag,Sale,AvailableOn}
# (AvailableOn ships with an interim apply — see Automatic collection regeneration;
# no schema change when its Phase 5 channel-aware reimplementation lands).
create_table :spree_collection_rules do |t|
t.references :collection, null: false
t.string :type, null: false
t.string :value
t.string :match_policy, null: false, default: 'is_equal_to'
t.timestamps
end
add_index :spree_collection_rules, [:collection_id, :type]
# Counter for ProductCollection membership (additive; the category-side
# counter renames happen in Phase 2).
add_column :spree_products, :collections_count, :integer, null: false, default: 0
# Mobility table-backend translations (mirrors spree_taxon_translations) for the
# table-backed translatable fields. NOT ActionText-specific: `description` uses the
# ActionText backend and is stored in the shared global `action_text_rich_texts` table.
create_table :spree_collection_translations do |t|
t.string :name
t.string :permalink
t.string :meta_title
t.string :meta_description
t.string :meta_keywords
t.string :locale, null: false
t.references :spree_collection, null: false, index: false
t.timestamps null: false
end
add_index :spree_collection_translations, :locale
add_index :spree_collection_translations, [:spree_collection_id, :locale], unique: true,
name: 'index_collection_translations_on_collection_and_locale'
end
end
1b. Models + code (built on 1a, fully spec'd before any rename):
Spree::Collection,Spree::ProductCollection,Spree::CollectionRule+ STICollectionRules::{Tag,AvailableOn,Sale}, all registered inconfig.spree.collection_rules(mirrors the existingconfig.spree.taxon_rules,engine.rb).AvailableOnships with the interim legacy-columnapply; channel-aware reimplementation is Phase 5Spree::Collections::RegenerateProducts;AutoMatchCollections(+ job) for event-driven regeneration on product save;RegenerateTimeBasedJob+time_based_collection_rules = [AvailableOn]registry (net-new — notaxon_rulesequivalent; taxons ship no scheduled refresh) for time-relative rules — all on thecollectionsqueue (see Design Details → Automatic collection regeneration)- Product:
in_collectionscope (+ ransack whitelist),collections/collections_count,primary_category - Store + Admin Collection API:
collectionscontrollers + serializers; dedicatedcollections/:id/products; admin nested curation + nestedreposition(the collection's own order reorders viapositionon update, no top-level reposition action);read_collections/write_collectionsAPI-key scopes;/products/filterscollection_idparam +FiltersAggregatorsort_order:change (see API → Collection product listing) - Meilisearch: index
collection_ids+ filterable/facet attrs +build_filter_condition+ reindex
Not in scope of this phase (or plan):
- Dashboard Collection UI — all dashboard work lives in
6.0-admin-spa.md(the Category admin UI is already there; Collection is added to its resource list). - Manual sort — implemented for both providers: DB (position ordering for category + collection groupings) and Meilisearch (single index +
distinctover per-grouping membership docs). All dynamic sorts work on both. (Was Open Question #1, now resolved.) CollectionRules::AvailableOn's channel-aware reimplementation — the model, its interim (legacy-column)apply, and the scheduled refresh (RegenerateTimeBasedJob+time_based_collection_rules) all ship in this phase; only rewritingapplyagainstProductPublication#published_atis Migration Phase 5, a dependency on6.0-channels-catalogs-b2b.md.
Phase 2: Table renames (Taxon → Category)
class RenameTaxonsToCategories < ActiveRecord::Migration[7.2]
def change
rename_table :spree_taxons, :spree_categories
rename_table :spree_products_taxons, :spree_product_categories
rename_column :spree_product_categories, :taxon_id, :category_id
# store_id already exists on spree_taxons (shipped 5.6) and carries over on
# the rename — do NOT re-add it. Backfill first:
# bundle exec rake spree:taxons:backfill_store_id
# Promotion↔category join + Mobility translations rename now too, so no class
# needs a table_name/foreign_key pin. (spree_taxon_rules + spree_prototype_taxons
# keep taxon_id — dropped in 6.1 / renamed by 6.0-product-types respectively.)
rename_table :spree_promotion_rule_taxons, :spree_promotion_rule_categories
rename_column :spree_promotion_rule_categories, :taxon_id, :category_id
rename_table :spree_taxon_translations, :spree_category_translations
rename_column :spree_category_translations, :spree_taxon_id, :spree_category_id
# Counter caches (category side): keep products_count (descendant-inclusive,
# already present); drop the direct classification_count (only the legacy Rails
# admin read it). collections_count was added additively in Phase 1.
remove_column :spree_categories, :classification_count, :integer
rename_column :spree_products, :classification_count, :categories_count
end
end
Transitional tweak. The tables are renamed here but the classes aren't renamed until Phase 3, so point the existing models at the renamed tables — otherwise the app and the Phase 4 rake task break in the middle state:
class Spree::Taxon < Spree.base_class
self.table_name = 'spree_categories' # Spree::Category < Spree::Taxon inherits it
end
class Spree::Classification < Spree.base_class
self.table_name = 'spree_product_categories'
belongs_to :taxon, class_name: 'Spree::Taxon', foreign_key: :category_id # column was renamed
end
spree_taxon_rules is not renamed — the new spree_collection_rules already exists (Phase 1); the old table is migrated in Phase 4 and dropped in 6.1 (Phase 6), not 6.0 (see Phase 3 for why).
Additional Phase 2 decisions (implemented):
classification_countis dropped now (not deferred). The direct taxon-side Rails counter was only read by the legacyspree/adminengine; the descendant-inclusiveproducts_countis kept. The product-side counter is renamedclassification_count→categories_count.Classification's counter_cache follows tocategories_count; the three taxon bulk services recomputeproducts_countviarecalculate_products_countinstead of the removed counter. Legacyspree/adminviews that readtaxon.classification_countare not fixed (that engine is being replaced by the SPA) — the specs they break are markedpending.- Mobility translation table is renamed here too (
spree_taxon_translations→spree_category_translations,spree_taxon_id→spree_category_id), for consistency with the other table renames. Once the class is renamed toSpree::Category(Phase 3), Mobility derivesspree_category_translations/spree_category_idnaturally, so notranslatespin is needed in delivered 6.0. (A Phase-2-only intermediate — class stillSpree::Taxon, table already renamed — would need a transient pin to the new table, but 6.0 ships all phases together.) - Automatic-taxon matching code is removed here (see Phase 3 rationale). Because 6.0 is single-delivery, the taxon auto-match path doesn't need to survive the rename: removed
Product#auto_match_taxons+after_commit,Product.bulk_auto_match_taxons,Taxon#regenerate_taxon_products+after_commit, and theTaxonRuleregeneration callback. Rule-based membership now lives onCollection.Pricere-match + the bulk-tags API endpoint now triggerauto_match_collections/Product.bulk_auto_match_collections; the bulk-category endpoints no longer re-match (category membership never affected rule matching). The service/job classesProducts::AutoMatchTaxons(+ its job) andTaxons::RegenerateProductsare retained as deprecating aliases (see Phase 3's "Deprecation aliases" note), not deleted. eligible_for_taxon_matching?→eligible_for_collection_matching?(theProductpredicate + thePriceattribute).
Phase 3: Class renames + deprecation aliases
Now that Collections exist (Phase 1) and the tables are renamed (Phase 2), rename the remaining classes and drop the transitional self.table_name tweaks from Phase 2. This runs before the data migration (Phase 4) so the migration script is written against the final model names (Spree::Category, Spree::ProductCategory, Spree::Collection) rather than the transitional ones. The inheritance is inverted today — Spree::Category < Spree::Taxon; the rename flips it: Spree::Category becomes the base class on spree_categories, and Spree::Taxon becomes the deprecation alias (removed in 6.1).
Spree::Taxon→Spree::Category(keepSpree::Taxonas a deprecation alias ofSpree::Categoryfor one release)Spree::Taxonomy→ deprecated, no replacementSpree::Classification→Spree::ProductCategory(alias for one release)Spree::PromotionRuleTaxon→Spree::PromotionRuleCategory;Spree::Promotion::Rules::Taxon→Spree::Promotion::Rules::Category(wire format is alreadycategory—api_type/category_ids— so the API contract is unchanged)- The rename is Ruby-level, not just class names: associations and methods go to
categorynow. The join models exposebelongs_to :category(ProductCategory,PromotionRuleCategory),Category/Productexposehas_many :product_categories, and the promotion rule exposeshas_many :promotion_rule_categories+has_many :categorieswith category-named internals (eligible_category_ids,category_ids_in_order_including_ancestors,add_categories,category_ids_to_add). Because Phase 2 renames the join tables too (spree_product_categories,spree_promotion_rule_categories,spree_category_translations+ theircategory_id/spree_category_idcolumns), noforeign_key/table_name/translatespins are needed — the naturalcategory_idis used everywhere and Mobility derivesspree_category_translationson its own. Pins remain only for the join tables that are not renamed in this plan:Category#has_many :prototype_taxons, foreign_key: :taxon_id(spree_prototype_taxonsis renamed by6.0-product-types.md) andCategory#has_many :taxon_rules, foreign_key: :taxon_id(spree_taxon_rulesis dropped in 6.1). Abelongs_to :taxon, foreign_key: :category_id— new name paired with a renamed column — is the exact backwards state to avoid. Product/Storekeepcategoriesas the one real, canonical association (-> { manual });taxonsis a deprecated method alias ofcategories, not a real association (removed in 6.1).taxonsis therefore dropped from the Product Ransack whitelist — filter bycategories_id_in(the v3 API uses thein_taxon/in_categoryscopes, nottaxons_ransack). Other deprecated method aliases bridge old names for one release:taxon/taxon=on the join models;taxons/taxon_ids/eligible_taxon_ids/taxon_ids_to_addon the rule;classificationsonProduct/Category.- Automatic-taxon matching code was removed in Phase 2, not here — since 6.0 ships all phases at once (no released intermediate state), the taxon auto-match services + triggers were deleted in Phase 2 and rule-based membership moved to
Collection.Spree::TaxonRule/TaxonRules::*remain as data-only models. - Dropping
spree_taxon_rules+Spree::TaxonRule/TaxonRules::*+ theconfig.spree.taxon_rulesregistry is deferred to 6.1 (Phase 6), NOT 6.0. The Phase 4 data migration readsspree_taxon_rulesto buildCollectionRules, but schema migrations (db:migrate) run automatically at deploy while the data migration is a manual rake task run afterward — a same-releasedrop_tablewould wipe the source before the data task runs. So the table + models are retained through 6.0 and dropped in 6.1. - Downstream shim:
alias_attribute :classification_count, :categories_counton Product for the deprecation window (any app reading the old column keeps working) - Update all serializers, controllers, services, factories, specs for the rename
- Stored class-name strings become
'Spree::Category'— the metafield/translation resource_type registries move to'Spree::Category', and renamed classes write the new name into polymorphic/STI/slug columns. Existing rows still hold'Spree::Taxon*'; they're backfilled by the Phase 4 data migration (see its step 4). This is a deliberate reversal of the Phase 2 pin-the-old-name approach — 6.0 does NOT keep using'Spree::Taxon'in data. - De-rule
Spree::Categoryat the model level (theautomatic/rules_match_policy/sort_ordercolumns +spree_taxon_rulestable stay for the Phase 4 migration, dropped in 6.1): removeproducts_matching_rules, thetaxon_rulesassociation +accepts_nested_attributes_for+rulesalias, therules_match_policy/sort_ordervalidations,scope :automatic, andmanual_sort_order?.SORT_ORDERS+RULES_MATCH_POLICIESmove toSpree::Collection(its rightful owner);FiltersAggregatorreadsSpree::Collection::SORT_ORDERS.scope :manual+ themanual?/automatic?column readers stay (the manual scope guards the category surfaces).TaxonRule#belongs_to :taxondrops its now-danglinginverse_of: :taxon_rules. - Brand removal (moved here from 6.1): delete
Product#brand_taxon/#brand_name(+ theMEMOIZED_METHODSentry), thebrandfield on the Products Performance report, and thebrand_namecolumn from the product CSV export — brands are out of scope with no replacement (see Key Decisions → Brands). Thespree_taxonomiestable +taxonomy_brands_namelocale key still drop in 6.1 withTaxonomy; only the brand methods/fields go now. - Wording sweep (Ruby names → category):
Product#main_taxon→#primary_category(deprecated delegate),touch_taxons→touch_categories,Spree::Products::TouchTaxonsJob→TouchCategoriesJob(both jobs later removed in 6.0 — see the deprecation shims below) +Spree.queues.taxons→categories(with a deprecation alias),taxon_and_ancestors→category_and_ancestors,remove_taxon→remove_category, thegrouped_taxon_ids_for_productsscope →grouped_category_ids_for_products, andrecalculate_products_count's param; delete the dead, buggyProduct#taxons_for_store. Comments/param names acrossCategory/Productde-taxoned. - Remove the deprecated taxon-tied
Productscopes marked remove-in-6.0:in_taxons,for_filters,taxons_name_eq, plus their now-orphaned private helpersprepare_taxon_conditions/get_taxons. The active scopes stay (in_taxon,in_category,in_categories,in_collection,ascend_by_taxons_min_position). Non-taxon deprecated scopes (master-price, option, name, etc.) are left for their own plans. - Rename the manual-membership services
Spree::Taxons::AddProducts/RemoveProducts→Spree::Categories::AddProducts/RemoveProducts(paramtaxons:→categories:, matchingSpree::Collections::*). All monorepo callers move to the new names, but the old classes are kept as deprecating aliases (see "Deprecation aliases" below). The optionalSpree::Taxons::TouchFeaturedSectionshook (guarded bydefined?, its namespace owned by another gem) is left untouched. - Deprecation aliases (kept for one release, removed in 6.1). Every renamed/moved taxon name keeps working with a runtime deprecation warning:
- Model constants (
Spree::Taxon,Spree::Classification,Spree::PromotionRuleTaxon,Spree::Promotion::Rules::Taxon) stay true constant aliases — notDeprecatedConstantProxy, which silently breaksis_a?/case/STI/polymorphic-constantize. Each callsSpree::Deprecation.warnin the alias's module body, so the notice fires through Spree's deprecator when the file loads (at boot under eager load, on first reference otherwise). Since a plain alias is the same object as the canonical class, a reliable per-reference warning isn't achievable without a proxy (breaksis_a?) orconst_missing(breaksdefined?), so the load-time notice is the deliberate trade-off. - Service/job classes are resurrected as thin deprecating wrappers that
Spree::Deprecation.warnon invocation and delegate:Taxons::AddProducts/RemoveProductstranslatetaxons:→categories:;Products::AutoMatchTaxons(+AutoMatchTaxonsJob) delegate to their*Collections*counterparts (Products::TouchTaxonsJobwas removed outright withTouchCategoriesJobin 6.0 — the Store API caches on product timestamps, so products no longer touch their categories);Taxons::RegenerateProductswarns and no-ops (categories are manual in 6.0 — its behavior only survives forCollection, keyed on a collection rather than a taxon, so there is no faithful delegate). Spree.queues.taxonsis restored as a singleton method that warns and returnsSpree.queues.categories.- Method bridges (
Product#taxons/taxon_ids/main_taxon/classifications,Store#taxons, the join models'#taxon, the rule's#taxons/#taxon_ids/#eligible_taxon_ids/#taxon_ids_to_add/#taxon_ids_string) eachSpree::Deprecation.warnand delegate. Internal core callers were repointed to the canonical names so the warnings only fire for external code. (Spree::TaxonomyandSpree::Taxons::Findare themselves legacy/dropped in 6.1 and keep referencing theTaxonconstant internally.)
- Model constants (
Phase 4: Data migration (rake task)
Runs after the Phase 2 rename and the Phase 3 class rename — so the script reads via the final models (Spree::Category, Spree::ProductCategory) and writes the final Collection classes, with everything in place. Classify by structure, not taxonomy name. Taxonomy names are Mobility-translated/localized and freely renamed, and default taxonomies are no longer auto-seeded (removed in 5.5, PR #14020) — so name matching is unreliable across upgraded and new stores alike. The real Category/Collection signal is already in the data: whether a category is rule-based.
# rake spree:migrate_taxons_to_categories_and_collections
#
# For every store, using store_id (backfill first — spree:taxons:backfill_store_id):
# 1. Automatic categories (automatic: true OR any taxon_rules) -> Spree::Collection
# - copy their TaxonRules -> new CollectionRules (remap collection_id, rewrite STI type)
# Maps ALL types 1:1 — Tag, Sale, AND AvailableOn. AvailableOn's CollectionRule
# model ships in Phase 1 (interim legacy-column apply), so its rows migrate cleanly
# with value + match_policy preserved; they go channel-aware once Phase 5 reimplements apply.
# - copy their ProductCategories -> ProductCollections
# - copy columns + metadata + table translations; MOVE the ActionText description,
# ActiveStorage image/square_image, metafields, and friendly_id slugs onto the
# collection (else category.destroy purges/destroys them). Match both
# 'Spree::Taxon' and 'Spree::Category' record_type/sluggable_type (deploy window).
# (regardless of which taxonomy / name they lived under)
# then delete the automatic rows from spree_categories (one txn per category, idempotent)
# 2. Manual categories stay as Spree::Category (the nested-set tree, owned via store_id)
# - manual categories that happened to live under a "Collections" tree stay as
# categories; merchants re-file them as collections via the new UI
# (safe, reversible — no name-based guessing)
# 3. Sever the taxonomy structure from the survivors: drop taxonomy roots left
# childless after step 1 (keep non-empty roots as top-level categories), then
# null taxonomy_id on all remaining categories — they are store-owned now.
# The taxonomy_id COLUMN + spree_taxonomies + the Taxonomy model drop in 6.1.
# 4. Backfill stored class-name strings 'Spree::Taxon*' -> 'Spree::Category*'
# (Phase 3 renamed the classes and writes the new names; existing rows still
# hold the old ones, so migrate them here):
# - spree_metafields.resource_type
# - spree_metafield_definitions.resource_type
# - friendly_id_slugs.sluggable_type
# - active_storage_attachments.record_type (taxon image / square_image)
# - action_text_rich_texts.record_type (description — translates :description, backend: :action_text)
# - spree_promotion_rules.type (Promotion::Rules::Taxon -> Category, STI)
# Direct FK columns (taxon_id/category_id) and the pinned translation table
# need no change. Same rake run as above, so no additional upgrade window.
# 5. Clean spree_product_type_categories (6.0-product-types.md): delete or
# re-point rows whose category moved to spree_collections or was a deleted
# taxonomy root — otherwise dangling category_id FKs survive the split
#
# Handles both upgraded stores (may have localized/renamed standard trees) and
# new 5.5+ stores (arbitrary or zero taxonomies).
Also owned by this plan's rename wave: flip Spree::ProductTypeCategory's
belongs_to :category, class_name: 'Spree::Taxon' to 'Spree::Category'
(the product-types plan ships before this rename and cannot do it itself).
Status: implemented as spree/core/lib/tasks/categories_and_collections.rake (spec: spec/lib/tasks/categories_and_collections_spec.rb). Each automatic category migrates in its own transaction — a partial failure rolls back and a re-run skips what's already gone, so the task is idempotent. Automatic categories with child categories are skipped (automatic taxons are leaves; the task refuses to destroy a subtree). After the automatic pass it severs the taxonomy structure (backfill store_id from taxonomy → drop childless taxonomy roots → null taxonomy_id on the rest), then runs the string backfills once for the surviving (manual) category rows.
Phase 5: Reintroduce channel-aware AvailableOn (after 6.0-channels-catalogs-b2b.md)
Gated on the channels plan finishing the available_on → ProductPublication#published_at migration. Until then, CollectionRules::AvailableOn runs the interim legacy-column query shipped in Phase 1.
- Reimplement
CollectionRules::AvailableOn#applyagainstspree_product_publications.published_at(join), replacing the rawspree_products.available_onquery. Decide which channel a store-owned collection's availability rule evaluates against — the store's default channel, or any publication withpublished_atin the window — and document it (a collection has no channel of its own). - No data migration, no registry change —
AvailableOnis already registered (Phase 1) and itsCollectionRulerows already carry the rightvalue/match_policyfrom Phase 4; onlyapplychanges. - Cross-plan ordering constraint (hard).
CollectionRules::AvailableOnis a reader ofspree_products.available_on, which6.0-channels-catalogs-b2b.mdPhase 3 ("6.0 cleanup") drops. This phase must land before that column drop — the channels plan's cleanup is blocked on this reimplementation.
Phase 5b: Taxonomy runtime removal (6.0) — shipped
Taxonomy is data-only from 6.0. Nothing creates, touches, or manages a taxonomy at runtime; the model and table survive purely so the 5.6 → 6.0 upgrade task can read existing rows (and so an interrupted upgrade can roll back). What landed:
Imports::CreateCategoriesJobbuilds store-owned categories — a CSV import no longer creates a taxonomy per path root. EveryA -> B -> Csegment is a category, the first one top-level, which matches what the data migration produces.Taxonomy timestamp touching removed —
Product#taxonomies(thehas_many through:) and thetaxonomy_idsmemoized method are gone; product-to-category touching was later removed altogether, along withTouchCategoriesJob.Taxonomy write-back callbacks removed —
Taxonomy#set_root/#set_root_taxon_nameandCategory#sync_taxonomy_name. Renaming a category no longer rewrites a taxonomy's name.Category#requires_taxonomy?and the taxonomy presence validation removed. The method always returnedfalse, so the taxonomy-scoped uniqueness branches were dead code — uniqueness is now unconditionally store-scoped, andcheck_for_rootandparent_belongs_to_same_taxonomyare gone.copy_taxonomy_from_parentstays: a category created under an un-migrated parent still inherits its taxonomy so#ensure_storeand.for_storecan resolve a store pre-upgrade.parent_belongs_to_same_taxonomydid carry one guarantee worth keeping, though — it stopped a category being nested under a parent from another store, as a side effect of taxonomies being store-owned.parent_belongs_to_same_storereplaces it directly: a tree belongs to one store, and while the API scopes parents by store, imports, extensions and direct model calls do not. It reads#storerather than the raw column so legacy rows still resolving their store through a taxonomy compare correctly.Unique indexes re-scoped to the store (
20260807150001_reindex_spree_categories_by_store). The(name, parent_id, taxonomy_id)/(permalink, parent_id, taxonomy_id)indexes stop constraining anything oncespree:migrate_taxons_to_categories_and_collectionsnullstaxonomy_id— SQL treats NULLs as distinct in unique indexes — and they never matched the store-scoped validation anyway.The replacement is a single unique index on
(permalink, store_id), and name uniqueness is dropped entirely. The permalink is the category's full path (men/clothing/shirts, built bygenerate_slugfrom the parent chain), so it already encodes the hierarchy: scoping it byparent_idwas always redundant, and two sibling categories that would clash are already caught because their paths are identical. Names need no constraint at all — the same name in two branches is legitimate, and the permalinks distinguish them.This also sidesteps the NULL problem that a
parent_id-scoped index creates. Top-level categories haveparent_id IS NULL, and unique indexes treat NULLs as distinct, so any index includingparent_idsilently fails to constrain roots — the common case in 6.0. Leavingparent_idout of the index removes the issue instead of working around it, so no partial indexes, no generated columns, and no per-adapter branching: one plain index behaves identically on PostgreSQL, SQLite, MySQL and MariaDB.Ordering is the normal one — migrations first, then rake tasks. That means the migration cannot depend on a rake task having cleaned the data for it; it resolves duplicate permalinks itself before adding the index (see below).
Duplicate permalinks are resolved by the migration itself (
Spree::CategoryPermalinkDeduplicator,spree/core/lib/spree/). Store-scoped uniqueness surfaced a real data hazard: pre-6.0 permalinks were unique per taxonomy, so one store could legally hold the same permalink under two taxonomies.This cannot be left to the upgrade rake task.
spree:taxons:backfill_store_idalready runs in the 5.5 -> 5.6 upgrade, so a 5.6 store reaches 6.0'sdb:migratewithstore_idpopulated — a collision would fail index creation and block the deploy before any rake task could run. The migration therefore deduplicates before adding the index.The deduplicator works on raw SQL, not
Spree::Category: a migration cannot assume the model's callbacks, validations and default scopes match the schema on disk. It groups by the store a category belongs to or resolves through its taxonomy, so rows still awaiting the backfill are covered too — which is whyspree:migrate_taxons_to_categories_and_collectionsstill calls it (its own backfill is what gives those rows a store, and assignment would otherwise trip the index row by row). The first category of each group keeps its permalink; the rest get their taxonomy's name appended, then a numeric suffix. Rewriting a permalink re-prefixes the whole subtree, so a child ofcatalogfollows its parent tocatalog-shop-b/kidsrather than keeping a path its parent no longer has. Idempotent — a second run is a no-op.Taxonomyderegistered fromtranslatable_resourcesandmetafields.enabled_resources, and dropped from the three permission sets — a model being removed shouldn't carry a user-manageable custom-field/translation surface.PermittedAttributes:taxonomy_attributesdeleted (unused);taxon_attributesrenamed tocategory_attributeswith a deprecatedtaxon_attributesreader delegating to it (removed 6.1). Thetaxonomy_idandtaxon_rules_attributeskeys are gone from it.Factories split —
:categoryis now its own store-owned factory that creates no taxonomy;:taxonremains the legacy taxonomy-backed factory (it builds its own root, since the model no longer does) for the upgrade-path specs.
No NULL-store_id fallbacks. Every category has a store_id: spree:taxons:backfill_store_id runs in the 5.5 -> 5.6 manifest, and #ensure_store — which landed in the same commit that made taxonomy optional — stamps one on create, so no row predates both. #store's taxonomy fallback, the .for_store taxonomy join, the [:taxonomy] preload and the serializers' c.taxonomy&.store_id filter were all written for a state that cannot occur, and are gone. This is what lets acts_as_nested_set be scoped by store (see above).
What deliberately stays until 6.1: the Taxonomy model + table (the upgrade task's source and rollback path), Category#taxonomy, and copy_taxonomy_from_parent, which keeps taxonomy_id consistent for that task. All three go with the column.
Phase 6: Cleanup (6.1)
- Remove all aliases and deprecation shims (incl. the
Spree::Taxonalias, theclassification_countalias_attribute, andPermittedAttributes.taxon_attributes) - Remove
taxonomy_idcolumn from categories - Remove
spree_taxonomiestable + thetaxonomy_idcolumn + thetaxonomy_brands_namelocale key (brands out of scope — no replacement;Product#brand_taxon/#brand_namewere already removed in 6.0/Phase 3) - Remove
automatic,rules_match_policy,sort_ordercolumns from categories (moved to collections), plus the deadhide_from_navcolumn (its Ruby/SDK surface went in 6.0 — see Key Decisions → Category) - Drop
spree_taxon_rules+Spree::TaxonRule/TaxonRules::*+ theconfig.spree.taxon_rulesregistry (retained data-only through 6.0 so the Phase 4 data migration can read them; rows were copied tospree_collection_rules, andCollectionRuleis net-new so there's no alias to keep) - Remove the deprecated Ruby-level aliases kept through 6.0: the
taxonsandclassificationsmethod aliases onProduct/Category/Store, thetaxon/taxon=readers on the join models, and the rule'staxons/taxon_ids/eligible_taxon_ids/taxon_ids_to_addaliases - Remove the deprecated constant + service/job/queue aliases kept through 6.0:
Spree::Taxon,Spree::Classification,Spree::PromotionRuleTaxon,Spree::Promotion::Rules::Taxon(constant aliases + their load-timeSpree::Deprecation.warn); theSpree::Taxons::AddProducts/RemoveProducts/RegenerateProducts,Spree::Products::AutoMatchTaxons/AutoMatchTaxonsJobwrappers; and theSpree.queues.taxonssingleton method - Rename
spree_prototype_taxons(with6.0-product-types.md), dropping theforeign_key: :taxon_idpin onCategory#prototype_taxons(the#taxon_rulespin goes away with thespree_taxon_rulesdrop above)
Constraints on Current Work
- Use
categoriesin all new API code. The Store API already does this. Don't introduce newtaxonreferences in API v3. - Use
Spree::Categoryin new code. It is the canonical class now;Spree::Taxonis a deprecation alias (removed in 6.1). - Don't add new TaxonRule subtypes.
TaxonRuleis data-only from 6.0 (matching removed); new rule types go onCollectionRule. - Don't add new Taxonomy-dependent features. Taxonomy is data-only from 6.0 (see Phase 5b) and dropped in 6.1 — don't read it, write it, or register it anywhere. The only permitted references are the upgrade rake tasks and the pre-upgrade store-resolution fallbacks.
- Keep the
ctg_prefix. Already in use, will carry over. - New "collection-like" (rule-based) features go on
Spree::Collection— the taxon automatic-match path was removed in Phase 2. ProductTypeCategoryjoin table (from 6.0-product-types.md) should be named anticipating the Category rename — usecategory_idcolumn, nottaxon_id. (Already satisfied:6.0-product-types.mdspecifiescategory_id.)- Counter reads use the new names. New code reads
products_count(inclusive) on Category /categories_counton Product — notclassification_count(being dropped/renamed). - No brand-specific features. Brands are out of scope for 6.0 (see Key Decisions → Brands). Don't add a
Spree::Brand, a brand column, a:brandstag context, or a categorykindcolumn; model brand grouping as a Category or Collection.
Open Questions
Resolved:
- Brand handling & Category kind/type column — 6.0 ships no brand feature and no
kindcolumn; brands are modeled as a regular Category or Collection, andbrand_taxon/brand_nameare removed withTaxonomy. See Key Decisions → Brands.- Collection product listing — a dedicated
GET /collections/:id/products(base visibility scope + an injectedin_collectionfilter, delegating to the shared search flow; default sort from the collection'ssort_order), with facets via the existing/products/filters+ a newcollection_idparam. See API → Collection product listing.- Automatic collection scheduling — a
RegenerateTimeBasedJobscoped to atime_based_collection_rulesregistry, scheduled by the host app (theExpireJobpattern). Ships in Phase 1 withAvailableOnas its one registered rule (interim legacy-column implementation; channel-aware reimplementation in Phase 5). See Design Details → Automatic collection regeneration.- Collection nesting — collections stay flat; hierarchy lives in Category (matches Shopify and keeps the Category/Collection split clean).
- "Manual" (position) sort in the v3 Store API — resolved for both providers.
- DB provider (shipped):
SearchProvider::Databaseinfers the grouping from the appliedin_category/in_collectionfilter (manual_sort_grouping), defaults a grouping page's blank sort tomanual, and orders byProductCollection.position(flat) for collections orMIN(ProductCategory.position)grouped per product (subtree collapse) for categories — reusing the join the filter already made, so no extra query.- Meilisearch provider — single index +
distinct(Algolia's "duplicate records" recipe).ProductPresenteremits, alongside each base doc, one membership doc per grouping (each collection + each category ancestor-or-self) carrying a shared scalargrouping_id+position; a manual grouping page filtersgrouping_idand sortsposition:asc, while an index-leveldistinctAttribute = product_idcollapses the duplicates on shop-all/search/non-manual queries. Facet counts + totals stay accurate underdistinct(verified on MS ≥ 1.40, incl. 1.42.1 and 1.49.0). Rejected alternatives: a two-index "membership index B" (extra index + dual-write; deferred as premature optimization — the escape hatch if thedistincttax hurts) and per-grouping nested sortable attributes (unbounded sortable list + reindex-per-grouping anti-pattern).
No open questions remain — all resolved above.
References
- Industry pattern: hierarchical Category + flat Collection (manual and/or rule-based) is the standard across modern headless commerce platforms
- Current Spree API: already uses
categoriesnaming in Store API v3 - Related plan:
6.0-product-types.md(ProductTypeCategory join table)