diff --git a/CHANGELOG.md b/CHANGELOG.md index e7eb044b..2282ddbd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ Features: associations for JSON and Attributes adapters via the `include` option (@NullVoxPopuli, @beauby). Fixes: +- [#1214](https://github.com/rails-api/active_model_serializers/pull/1214) retrieve the key from the reflection options when building associations (@NullVoxPopuli, @hut8) Misc: - [#1178](https://github.com/rails-api/active_model_serializers/pull/1178) env CAPTURE_STDERR=false lets devs see hard failures (@bf4) diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index 86c5752c..af627a13 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -92,7 +92,8 @@ module ActiveModel Enumerator.new do |y| self.class._reflections.each do |reflection| - next unless include_tree.key?(reflection.name) + key = reflection.options.fetch(:key, reflection.name) + next unless include_tree.key?(key) y.yield reflection.build_association(self, instance_options) end end diff --git a/test/action_controller/json_api/linked_test.rb b/test/action_controller/json_api/linked_test.rb index 04ea4c99..8d541f5b 100644 --- a/test/action_controller/json_api/linked_test.rb +++ b/test/action_controller/json_api/linked_test.rb @@ -46,6 +46,11 @@ module ActionController render json: @post, include: [:author], adapter: :json_api end + def render_resource_with_include_of_custom_key_by_original + setup_post + render json: @post, include: [:reviews], adapter: :json_api, serializer: PostWithCustomKeysSerializer + end + def render_resource_with_nested_include setup_post render json: @post, include: [comments: [:author]], adapter: :json_api @@ -137,6 +142,18 @@ module ActionController assert_equal expected_linked, response['included'] end + def test_render_resource_with_include_of_custom_key_by_original + get :render_resource_with_include_of_custom_key_by_original + response = JSON.parse(@response.body) + assert response.key? 'included' + + relationships = response['data']['relationships'] + + assert_includes relationships, 'reviews' + assert_includes relationships, 'writer' + assert_includes relationships, 'site' + end + def test_render_resource_with_nested_include get :render_resource_with_nested_include response = JSON.parse(@response.body)