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.

8.5 KB
Raw Blame

Store-scoped Custom Field Definitions + persisted filter_key

Status: Implemented (2026-09-02) Target: Spree 6.0 Depends on: 5.4-6.0-custom-fields-rename.md, 5.6-6.0-single-store-promotions-payment-methods.md Author: Damian Legawiec Last updated: 2026-09-02

Summary

Spree::CustomFieldDefinition (renamed from Spree::MetafieldDefinition by the custom-fields rename) was global — it had no store_id, and nothing scoped it by store. Every store in an installation shared one custom-field schema, and the Admin API let any store's staff read and edit every other store's definitions.

Two related changes were deferred here from the 5.6 custom-field search/sort/filter work (that PR shipped as a patch release and these are schema changes):

  1. store_id on definitions — make custom-field schema store-owned, matching the single-owner direction already taken for Product, Promotion, and PaymentMethod.
  2. Persist filter_key — the cf_<namespace>_<key> identifier used to sort and filter product listings was computed in Ruby on every call. A column lets it be uniquely indexed and looked up directly.

Together they make uniqueness (store_id, resource_type, filter_key), enforced by both a model validation and a DB unique index.

Key Decisions (do not deviate without discussion)

  • filter_key is the name, not search_key — the value drives sorting and filtering, not just text search. full_key was already taken: it returns the dotted custom.material form used by CSV headers (custom_field.custom.material) and the Store API's key field, and must not be repurposed.
  • Format stays cf_<namespace>_<key>. Not cf_<namespace.length>_... (the original length-delimited form, dropped as unreadable) and not the definition's prefixed ID (opaque, and not portable across environments).
  • Uniqueness needs enforcing either way. key is already unique per (store_id, resource_type, namespace), but both segments normalize to underscored slugs, so ("a_b", "c") and ("a", "b_c") both flatten to cf_a_b_c — one of them would be unaddressable. This was a CONCAT-based validation with no index behind it; it is now a plain uniqueness validation plus a unique index.
  • Definitions get a has_many on Store, not a for_store scope of their own — the association is the scoping mechanism (store.custom_field_definitions). Spree::SingleStoreResource supplies the belongs_to, the Spree::Current fallback and the immutable-owner guard, and Spree::Base.for_store resolves through the association, so the Admin API controller became store-scoped without an override.

Settled 2026-09-02

  • Existing definitions all move to the default store, rather than being copied per store. Copies would have produced N duplicate rows whose values still pointed at the originals, so every non-default store would show the same blank fields it shows under the simpler backfill — at N times the rows, plus a re-pointing pass over spree_custom_fields. Multi-store operators re-create the fields they want on their other stores.
  • The migration backfills and enforces null: false itself. Shipping the columns nullable would void the unique index outright — SQL treats NULLs as distinct, so uniqueness would look enforced while not holding. Follows the return/refund reason precedent already shipped in 6.0; spree:upgrade:backfill_custom_field_definition_stores is the recovery path for installs whose migration ran before any store existed.
  • A custom field's value is validated to agree with its definition's store (revised during implementation — the original ruling was the opposite). The premise, that every path resolving a definition is store-scoped, was false: Rails' own accepts_nested_attributes_for writer assigns custom_field_definition_id straight onto the row and reaches no resolver. The check lives on Spree::CustomField beside the resource_type agreement check already there, and skips resources with no store of their own — a customer and an address are global, and were resolved within a store on the way in.

Design Details

Schema

add_reference :spree_custom_field_definitions, :store   # backfilled, then null: false
add_column    :spree_custom_field_definitions, :filter_key, :string   # backfilled, then null: false

add_index :spree_custom_field_definitions, [:store_id, :resource_type, :filter_key],
          unique: true, name: 'index_custom_field_definitions_on_store_and_filter_key'

The pre-existing (resource_type, namespace, key) unique index is replaced by a store-scoped one.

Model

  • Spree::Store gains has_many :custom_field_definitions, dependent: :destroy_async.
  • Spree::CustomFieldDefinition includes Spree::SingleStoreResource and gains a before_validation :set_filter_key callback, so the value follows a renamed namespace or key.
  • filter_key is read from the column, falling back to the computed form for an unsaved record whose callback has not run yet.

Call sites that became store-scoped

All of these fetched definitions with for_resource_type and no store filter. The CSV pairs must stay in lockstep or header and value columns misalign:

Location Note
Spree::Export#custom_fields_headers header row
Spree::Product#to_csv value row — takes the store the export runs for
Spree::Order#to_csv value row — its store argument was ignored (_store)
Spree::CSV::CustomFieldsHelper customer / gift card / newsletter presenters
Spree::Import#custom_field_definitions_for_model
Spree::Product.search scope
Spree::SearchProvider::CustomFieldSchema takes a store constructor argument
Spree::HasCustomFields.ensure_custom_field_definition_exists! auto-creates — needs a store
Spree::HasCustomFields#resolve_custom_field_definition_id_from_string auto-creates via the "namespace.key" form
Spree::Imports::RowProcessors::ProductVariant definition lookup per CSV column
Api::V3::Admin::CustomFieldDefinitionsController store-scoped through for_store, no override needed
Spree::ProductTypeCustomFieldDefinition the join validates that both sides belong to one store
Spree::SellerRequirements::RequiredCustomFields definitions picked for a requirement come from the requirement's store

Backfill

spree:upgrade:backfill_custom_field_definition_stores, registered in the 5.6→6.0 manifest, is the recovery path when the migration ran with no store present:

  • Assign store_id = Spree::Store.default.id to every definition missing one.
  • Populate filter_key on rows still missing it.
  • Report and skip rows whose namespace/key pair collides with an already-backfilled row in the same store; only one can own the key. The operator renames one of each pair and re-runs. Idempotent.

Constraints on Current Work

  • Never read Spree::CustomFieldDefinition unscoped. Go through store.custom_field_definitions. The table now carries a store_id, so Spree::StoreScopeGuard watches it and an unscoped scan raises in the API suite. A deliberately global lookup wraps in Spree::StoreScopeGuard.skip { } and needs a reason.
  • Don't add a for_store scope to CustomFieldDefinition — the has_many on Store is the mechanism, and Spree::Base.for_store already resolves through it.
  • CSV headers and values must come from one store's definitions. They are produced in different objects (Spree::Export and the record's to_csv); if the two disagree about the store the columns silently misalign.
  • filter_key is derived, never client-writable. It is set by the callback from namespace and key; the Admin API does not permit it.
  • A definition's store is immutable once set (SingleStoreResource's guard). Moving a definition between stores would orphan every value pointing at it.

Open Questions

None — the three that stood were settled 2026-09-02 (see Key Decisions).

spree_multi_store may still want to share definitions across stores the way it does for promotions and payment methods. If so the sharing bridge belongs in that extension, not core.

References

  • docs/plans/5.4-6.0-custom-fields-rename.md — the Metafield → CustomField rename
  • docs/plans/5.6-6.0-single-store-promotions-payment-methods.md — the same single-owner migration for Promotion and PaymentMethod
  • docs/developer/core-concepts/metafields.mdx — search/sort/filter docs