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.

Fixed `expand` parameter in API with aliased assocations (#13869)

Damian Legawiec1685c048e024
diff --git a/spree/api/app/serializers/spree/api/v3/base_serializer.rb b/spree/api/app/serializers/spree/api/v3/base_serializer.rb
index c64a49c141..1a0a112652 100644
--- a/spree/api/app/serializers/spree/api/v3/base_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/base_serializer.rb
@@ -60,10 +60,12 @@ module Spree
private
# Override Alba's fetch_attribute to automatically inject nested expand params
- # into child serializers via nested_params
+ # into child serializers via nested_params.
+ # Uses `key` (the public API name, e.g. :categories) for expand lookup,
+ # not `attribute.name` (the internal association name, e.g. :taxons).
def fetch_attribute(obj, key, attribute)
if attribute.is_a?(Alba::Association)
- nested = nested_params(attribute.name)
+ nested = nested_params(key)
yield_if_within(attribute.name.to_sym) { |within| attribute.to_h(obj, params: nested, within: within) }
else
super
diff --git a/spree/api/spec/controllers/concerns/spree/api/v3/nested_expand_spec.rb b/spree/api/spec/controllers/concerns/spree/api/v3/nested_expand_spec.rb
index 2ac09f4afb..e9c54cef21 100644
--- a/spree/api/spec/controllers/concerns/spree/api/v3/nested_expand_spec.rb
+++ b/spree/api/spec/controllers/concerns/spree/api/v3/nested_expand_spec.rb
@@ -73,6 +73,38 @@ RSpec.describe Spree::Api::V3::Store::ProductsController, type: :controller do
end
end
+ describe 'nested expand on aliased associations (key differs from name)' do
+ let!(:taxonomy) { create(:taxonomy, store: store) }
+ let!(:parent_taxon) { create(:taxon, taxonomy: taxonomy, parent: taxonomy.root) }
+ let!(:child_taxon) { create(:taxon, taxonomy: taxonomy, parent: parent_taxon) }
+
+ before do
+ product.taxons << child_taxon
+ end
+
+ it 'expands categories with nested ancestors' do
+ get :show, params: { id: product.prefixed_id, expand: 'categories.ancestors' }
+
+ data = JSON.parse(response.body)
+ expect(data).to have_key('categories')
+ expect(data['categories']).to be_an(Array)
+ data['categories'].each do |category|
+ expect(category).to have_key('ancestors')
+ expect(category['ancestors']).to be_an(Array)
+ end
+ end
+
+ it 'expands categories without ancestors when only categories requested' do
+ get :show, params: { id: product.prefixed_id, expand: 'categories' }
+
+ data = JSON.parse(response.body)
+ expect(data).to have_key('categories')
+ data['categories'].each do |category|
+ expect(category).not_to have_key('ancestors')
+ end
+ end
+ end
+
describe 'collection endpoint' do
it 'supports nested expand on index' do
get :index, params: { expand: 'variants.media' }