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.
Drop Country/State AR Models — ISO Codes Everywhere
Status: Implemented for 6.0 — everything but the 6.1 table drop — see "Implementation status"
Target: Spree 6.0 (physical table/column drop: 6.1)
Depends on: 6.0-tax-provider.md Phase 5 (amended by this plan — TaxRate columns are born as ISO strings, see Key Decisions; shipped)
Author: Damian + Claude
Last updated: 2026-08-14
Summary
Delete the Spree::Country and Spree::State ActiveRecord models and their tables. Countries and subdivisions become gem-backed value objects served from the countries gem (ISO3166::Country), and every consumer stores plain ISO codes (country_code, state_abbr) instead of foreign keys. This matches the whole industry: none of Shopify, Medusa, Vendure, or Saleor points an address at a state row, and the two that keep a country table (Medusa, Vendure) treat it as a materialized cache of a static ISO list, not merchant data. Our own public surface is already there — the v3 API exposes no id for either model, serializes addresses as flat country_code/state_abbr/state_name strings, and the dashboard submits ISO codes only — so the change is internal to the Ruby layer apart from the field renames recorded under Naming.
Implementation status (2026-08-14)
Shipped. Spree::Country and Spree::State are plain value objects backed by the countries gem; carmen, the country/state seeds, and the row-creating fallbacks (Store#default_country_code=, Stores::Markets#create_fallback_country) are gone. Every consumer stores and matches on ISO codes: country_code / state_code columns on addresses, delivery zone members, market countries, stock locations and stores, filled by spree:upgrade:migrate_country_state_codes (in the 5.6→6.0 manifest after the delivery-zone conversion). Spree::IsoData is the curated reference registry, covered by a guard spec that replays the old Carmen seed and fails if any code it produced stops resolving. The country endpoints dropped their conditional GETs, the admin address endpoints stopped accepting raw foreign keys, and the test factories build real countries and real subdivisions. The v3 contract changed only in the field names (see Naming below); the suites pass with the renames applied.
Naming (2026-08-14, extended 2026-08-15): country_code + state_code is the one pair — column, model, and v3 API, store side included. Both halves read as one decision; the earlier country_iso/state_code split was defensible (a country code is a complete ISO 3166-1 value, a subdivision code is only the second segment) but nobody reading the API would infer it, and no other platform says country_iso — Shopify, Medusa, Vendure and Saleor all say country_code. 6.0 is the breaking window, so the rename is not hidden behind an alias: stock locations, delivery zone members, market countries, tax rates, tax lines, tax exemption certificates and every new model speak country_code/state_code only, and Market exposes country_codes. The single exception is Spree::Address, which keeps country_iso and state_abbr as deprecated alias_attributes, deprecated read attributes on the store AddressSerializer, and accepted write params — storefronts shipped against those names. 6.1 removes them.
Spree::Store collapses the odd column/virtual split at the same time: the column is default_country_code (was default_country_iso_code) and the market-aware reader carries that name, with default_country_iso_code and the virtual default_country_iso= kept as deprecated shells until 6.1. Promotion::Rules::Country renames its preferences to country_codes/country_code, and because preference keys are stored data rather than schema, reads fall back to the old country_isos/country_iso keys so rules saved earlier keep matching.
One concern, no duplication (2026-08-14): Spree::HasIsoGeography (included into Spree::Base, the has_spree_number pattern) is the single declaration for code-storing models — has_iso_geography gives upcasing normalization, ISO validation of both codes (state checked against its country, gated on change so historical rows stay updatable) and registry-backed country/state readers; state: false for country-only tables. Declared by Address, StockLocation, DeliveryZoneMember, MarketCountry, TaxRate, TaxLine and TaxExemptionCertificate. Only Spree::Address layers object writers (country=/state=) on top — everything else assigns codes; the stock-location, zone-member and market-country object writers are gone, and test factories carry country:/state: as transients mapped to codes.
What became of the tax gate. The tax-provider Phase 5 rewrite shipped on main: TaxRate matches on country_code/state_code scopes and nothing at runtime reads Spree::Zone any more. Spree::Zone/Spree::ZoneMember survive purely as migration-only shells — no polymorphic zoneable association, no matching; the 5.6→6.0 data tasks (migrate_zones_to_delivery_zones, migrate_checkout_zones, migrate_tax_zones) resolve member ids directly against the legacy spree_countries/spree_states tables via SQL. Both shells drop in 6.1 with the tables.
Key Decisions (do not deviate without discussion)
- The
countriesgem is the sole data source (resolved 2026-08-07).ISO3166::Countryalready powers localized names, currency, and locale at runtime today; it also carries subdivisions, so it absorbs what Carmen seeded.carmenis removed from the gemspec entirely. No vendored data file — we accept the gem as a dependency we already have. Spree::CountryandSpree::Statekeep their constant names but become plain Ruby value objects (ActiveModel::Model+ActiveModel::Attributes, same pattern asSpree::PickupPointOption).Spree::Country.by_iso('US'),#name,#states,#states_required?,#zipcode_required?,#localized_name,#default_currencyall survive with the same signatures. ActiveRecord calls (.where,.find, associations) fail loudly withNoMethodError— acceptable in the 6.0 breaking window, and better than silently different query semantics.- Address validation semantics are preserved exactly (resolved 2026-08-07). For
STATES_REQUIREDcountries the submittedstate_abbrmust match a gem subdivision code, and astate_namematching a subdivision name is still promoted to its code; for every other countrystate_namestays free text. TheSTATES_REQUIREDandNO_ZIPCODE_ISO_CODESconstants onSpree::Address— already the seed-time source of truth — become the runtime source of truth. A Google-address-ruleset upgrade (Saleor'si18naddressapproach) is explicitly out of scope; the validation seam is designed so it can slot in later. - Tables drop in 6.1, not 6.0 (resolved 2026-08-07, revised 2026-08-13). Code switches to ISO strings in 6.0, but
spree_countries/spree_statesand everycountry_id/state_idcolumn survive the release:spree:upgrade:migrate_country_state_codesreads them to fill the ISO columns, so dropping them in the same release would leave the upgrade task nothing to read on exactly the installs that need it. Same pattern as the returns-chain tables. See the Migration Path for the authoritative sequencing. 6.0-tax-provider.mdPhase 5 is amended before it ships (resolved 2026-08-07).spree_tax_rates(and laterTaxExemptionCertificate) getcountry_code/state_abbrstring columns, nevercountry_id/state_idFKs. Verified 2026-08-07 that the FK columns do not exist yet — amending now converts a double migration into a saving. The "state-level rate overrides country-level" precedence rule carries over to string matching unchanged.- Subdivision codes are only meaningful with their country. Every table storing a
state_abbralso stores thecountry_code(spree_addresses,spree_delivery_zone_members,spree_stock_locations, tax rates). Abbreviations are not globally unique (CAis California and several other things); the pair is the identifier. This also fixes the existing bug where the admin delivery-zones controller resolved a bare abbr againstSpree::Stateglobally. - The v3 API contract does not change. Country/State are already the only v3 resources addressed by natural key with no prefixed ID; serializers keep emitting
iso/iso3/name/states_required/zipcode_requiredandabbr/name. Controllers keep the same routes, params, and caching; only their backing store changes. One accepted value drift:namenow comes from the gem's CLDR data instead of the Carmen-seeded column, so a few country names may read slightly differently. The dashboard already prefers the browser'sIntl.DisplayNamesover the APIname, so admin UI display is unaffected. - The two admin endpoints that still accept raw
country_id/state_idparams drop them (admin customer addresses, admin order addresses). They were the only place integer FKs crossed the wire; every other endpoint is already ISO-only. - The two ISO→record resolution paths are unified first. Today
Spree::Addresses::Helpersilently nils an unrecognized ISO while theAddressmodel callbacks no-op; after this plan there is one normalization path on the model, and an unrecognized code is a validation error, never silent data loss.
Design Details
The value objects
# Same constants, no longer ActiveRecord
class Spree::Country
include ActiveModel::Model
include ActiveModel::Attributes
attribute :iso, :string # 'US' — the identifier
attribute :iso3, :string
attribute :numcode, :integer
def self.all # memoized list from ISO3166::Country.all, minus EXCLUDED_COUNTRIES
def self.by_iso(code) # matches iso OR iso3, case-insensitive (same as today); nil on miss
def self.find_by_iso!(code) # raising variant for controllers (404 path)
def name # ISO3166 CLDR translation for the current locale
def states # ISO3166::Country[iso].subdivisions → [Spree::State]
def states_required? # Spree::Address::STATES_REQUIRED.include?(iso)
def zipcode_required? # !Spree::Address::NO_ZIPCODE_ISO_CODES.include?(iso)
def default_currency / default_locale / localized_name(locale:) # unchanged, already gem-backed
end
class Spree::State
attribute :abbr, :string # subdivision code without country prefix ('CA', not 'US-CA')
attribute :name, :string
attribute :country_code, :string # always present — abbr alone is ambiguous
end
The country list is process-memoized and immutable. EXCLUDED_COUNTRIES (the nine territories the seeds skip today) moves from Spree::Seeds::Countries onto the registry. Sorting where the DB did order(:name) becomes an in-Ruby sort on localized names — fine at ~250 entries, and now correctly locale-aware where the DB sort never was.
Column conversions
| Table | Today | After |
|---|---|---|
spree_addresses |
country_id (FK, required), state_id (FK, optional), state_name |
country_code (null: false), state_code, state_name (unchanged) |
spree_delivery_zone_members |
country_id, state_id |
country_code, state_code — state members now carry both |
spree_market_countries |
country_id |
country_code; uniqueness (market_id, country_code) |
spree_stock_locations |
country_id, state_id |
country_code, state_code |
spree_stores |
default_country_id |
default_country_code |
spree_states |
country_id |
table dropped |
spree_tax_rates (unshipped) |
— (plan specced FKs) | born as country_code, state_code |
ISO codes are stored upcased 2-letter; state_code upcased without the country prefix (matches today's seeded values, the API contract, and what the dashboard submits).
Address
The model keeps its public shape: country_code/state_code stop being buffered virtual writers resolved through before_validation lookups and become the actual columns. country_name, country_iso3, state_text, state_name_text, require_zipcode?, gateway_hash all read through the value objects. state_validate keeps its exact decision tree, backed by country.states from the gem instead of country.states from the DB. Spree::Addresses::Helper's duplicate resolution logic is deleted; Addresses::Create/Update pass the ISO params straight to the model.
Ransack: whitelisted_ransackable_associations drops country/state; country_code and state_code join the ransackable attributes so existing admin filtering keeps working as plain string predicates.
Consumers, converted
DeliveryZoneMember#match?— string comparison instead of FK integers:address.country_code == country_code, and for state memberscountry_code+state_codeboth.range_capable_country_codesis already an ISO allowlist. The admin controller's ISO→FK conversion layer is deleted.Store#countries_with_shipping_coverage— the state→country SQL hop disappears because state members now carry their owncountry_code: the query becomes a union of membercountry_codevalues, hydrated through the registry and sorted by localized name.Market/MarketCountry—country_codes(already the API façade) becomes the storage reality.for_countrytakes an ISO,default_countrypicks first by localized name, both cross-market validations (country_unique_per_store,country_covered_by_shipping_zone) become string queries.Store#default_countryreturns a value object;default_country_code=stops creating rows (it can't — there are no rows), as does the market-bootstrapcreate_fallback_country. Fallback is simplySpree::Country.by_iso('US'), which always exists.StockLocation— same conversion as Address; its ISO writers already exist.Carts::Update#clear_shipping_address_if_outside_market— comparescountry_codestrings instead ofcountry_ids.Promotion::Rules::Country— already ISO-native; only its display-hydration helper switches to the registry. This class was the template for the whole refactor.- Zone / ZoneMember — not converted. They are removed by
6.0-delivery-zones.mdPhase D before this plan's final phase; the polymorphic member design never gets a string rewrite.
Seeds, factories, test support
Spree::Seeds::Countries and Spree::Seeds::States are deleted (nothing to seed). The country/state factories are deleted; factories that built them (address, delivery_zone, market, stock_location, zone, cart, order_walkthrough) switch to literal ISO strings — which also kills a long-standing factory smell (every factory country claimed numcode: 840, and the state factory could grab any of them). testing_support/store.rb drops the suite-wide @default_country record.
Migration Path
Sequenced inside 6.0, after 6.0-fulfillment-and-delivery.md's shipped surface and interleaved with the tax/zone work:
- ✅ Docs first: amend
6.0-tax-provider.mdPhase 5 to string columns, record the decision indecisions.md, superseding notes in6.0-delivery-zones.mdand6.0-admin-api.md. - ✅ Safe pre-work (independent of everything): close the admin
country_id/state_idparam leak; unify the two ISO resolution paths onto the Address model. - ✅ The registry:
Spree::IsoDataplus the guard spec that replays the old seed, and theISO3166locale configuration (inafter_initialize, not an initializer —Spree.available_localesis not populated that early). - ✅ String columns + backfill: the new
*_iso/*_abbrcolumns;spree:upgrade:migrate_country_state_codesin the 5.6→6.0 manifest, resumable viawhere(country_code: nil); every reader and validation converted. - ✅ Test data: factories build real countries and real subdivisions, with postal codes their country accepts.
- ⏸ Registry swap — blocked on
Spree::Zone: replace the AR models with the value objects and delete the seeds, thecarmendependency and the row-creating fallbacks. Needs6.0-tax-provider.mdPhase 5 and then6.0-delivery-zones.mdPhase D. - ⏸ Drop — deferred to 6.1 (2026-08-13):
spree_countries,spree_states, and every legacycountry_id/state_id/default_country_idcolumn. The tables survive 6.0 as the upgrade task's source data —spree:upgrade:migrate_country_state_codesreads them to fill the ISO columns, and dropping them in the same release would leave the task nothing to read on exactly the installs that need it. Same pattern as the returns-chain tables. Nothing writes them in 6.0;spree_market_countries.country_idis relaxed to nullable since rows are created without it.
Tax Phase 5 slots in wherever it lands on its own schedule — with the amendment it creates string columns directly and needs nothing from steps 3–5. It is, however, what unblocks steps 6 and 7.
Constraints on Current Work
- No new
country_id/state_idFK columns orbelongs_to :country/:stateassociations anywhere. New features storecountry_code(+state_codewhere subdivisions matter, always as a pair) — thePromotion::Rules::Country/DeliveryZoneMember.range_capable_country_codespattern. - Tax-provider Phase 5 implements the amended spec (string columns) — the FK version in older revisions of that plan is superseded.
- Don't build anything on Country/State being queryable ActiveRecord — no new Ransack predicates through the
country/stateassociations, no new joins tospree_countries/spree_states, no code that creates Country rows. - Address-adjacent code reads geography through the model's ISO accessors (
country_code,state_code,state_text), never throughaddress.country.idor the state association.
Open Questions
- Per-country address form rules (Google ruleset /
i18naddress) — deliberately deferred. The validation seam (country.states_required?+ subdivision list) is where it would plug in; unblocked by real demand for per-country field ordering/labels ("prefecture" vs "state") beyond whatSTATES_REQUIREDcovers. - Bundling a static country list in the dashboard instead of the API fetch — deferred; the API contract is unchanged so nothing forces it. Revisit only if the extra request at dashboard boot ever matters.
References
docs/plans/decisions.md2026-08-07 entry (this decision)docs/plans/6.0-tax-provider.md— Phase 5 (amended to string columns)docs/plans/6.0-delivery-zones.md— Phase D is the sequencing gate; member FKs converted heredocs/plans/6.0-admin-api.md— countries endpoints (contract unchanged)- Competitor survey (2026-08-07): Shopify
MailingAddress(countryCodeV2enum + province strings), Medusa v2region_country(static 251-entry list upserted at boot, PKiso_2, free-stringprovince), VendureCountry/Province extends Region(Province unseeded and never referenced by Address —provinceis a string column), Saleordjango-countries+i18naddress(no tables at all)