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.
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):
store_idon definitions — make custom-field schema store-owned, matching the single-owner direction already taken for Product, Promotion, and PaymentMethod.- Persist
filter_key— thecf_<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_keyis the name, notsearch_key— the value drives sorting and filtering, not just text search.full_keywas already taken: it returns the dottedcustom.materialform used by CSV headers (custom_field.custom.material) and the Store API'skeyfield, and must not be repurposed.- Format stays
cf_<namespace>_<key>. Notcf_<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.
keyis 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 tocf_a_b_c— one of them would be unaddressable. This was aCONCAT-based validation with no index behind it; it is now a plain uniqueness validation plus a unique index. - Definitions get a
has_manyon Store, not afor_storescope of their own — the association is the scoping mechanism (store.custom_field_definitions).Spree::SingleStoreResourcesupplies thebelongs_to, theSpree::Currentfallback and the immutable-owner guard, andSpree::Base.for_storeresolves 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: falseitself. 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_storesis 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_forwriter assignscustom_field_definition_idstraight onto the row and reaches no resolver. The check lives onSpree::CustomFieldbeside theresource_typeagreement 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::Storegainshas_many :custom_field_definitions, dependent: :destroy_async.Spree::CustomFieldDefinitionincludesSpree::SingleStoreResourceand gains abefore_validation :set_filter_keycallback, so the value follows a renamed namespace or key.filter_keyis 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.idto every definition missing one. - Populate
filter_keyon 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::CustomFieldDefinitionunscoped. Go throughstore.custom_field_definitions. The table now carries astore_id, soSpree::StoreScopeGuardwatches it and an unscoped scan raises in the API suite. A deliberately global lookup wraps inSpree::StoreScopeGuard.skip { }and needs a reason. - Don't add a
for_storescope toCustomFieldDefinition— thehas_manyon Store is the mechanism, andSpree::Base.for_storealready resolves through it. - CSV headers and values must come from one store's definitions. They are
produced in different objects (
Spree::Exportand the record'sto_csv); if the two disagree about the store the columns silently misalign. filter_keyis derived, never client-writable. It is set by the callback fromnamespaceandkey; 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 renamedocs/plans/5.6-6.0-single-store-promotions-payment-methods.md— the same single-owner migration for Promotion and PaymentMethoddocs/developer/core-concepts/metafields.mdx— search/sort/filter docs