From 965a9cb568228e4e3e26a96ff7fa018d9a2ea6e6 Mon Sep 17 00:00:00 2001 From: Yuri Ratanov Date: Fri, 27 May 2022 10:11:58 +0700 Subject: [PATCH] fix empty belongs_to with polymorphic serialization error Happened when jsonapi_use_foreign_key_on_belongs_to_relationship=true --- .../adapter/json_api/relationship.rb | 1 + test/serializers/associations_test.rb | 35 +++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/lib/active_model_serializers/adapter/json_api/relationship.rb b/lib/active_model_serializers/adapter/json_api/relationship.rb index 2879e3eb4..c23c332a8 100644 --- a/lib/active_model_serializers/adapter/json_api/relationship.rb +++ b/lib/active_model_serializers/adapter/json_api/relationship.rb @@ -51,6 +51,7 @@ def data_for_one(association) if association.polymorphic? # We can't infer resource type for polymorphic relationships from the serializer. # We can ONLY know a polymorphic resource type by inspecting each resource. + return unless association.lazy_association.serializer association.lazy_association.serializer.json_key else association.reflection.type.to_s diff --git a/test/serializers/associations_test.rb b/test/serializers/associations_test.rb index a86b7a3f4..0c8f06e3a 100644 --- a/test/serializers/associations_test.rb +++ b/test/serializers/associations_test.rb @@ -174,6 +174,41 @@ def blog_id assert_equal expected, actual end + class BelongsToPolymorphicBlogModelSerializer < ActiveModel::Serializer + type :posts + belongs_to :blog, polymorphic: true + end + + def test_works_for_empty_polymorphic_relationship + attributes = { id: 1, title: 'Belongs to Blog', blog: Blog.new(id: 5) } + post = BelongsToBlogModel.new(attributes) + class << post + def blog + nil + end + + def blog_id + nil + end + + def blog_type + nil + end + end + + actual = + begin + original_option = BelongsToPolymorphicBlogModelSerializer.config.jsonapi_use_foreign_key_on_belongs_to_relationship + BelongsToPolymorphicBlogModelSerializer.config.jsonapi_use_foreign_key_on_belongs_to_relationship = true + serializable(post, adapter: :json_api, serializer: BelongsToPolymorphicBlogModelSerializer).as_json + ensure + BelongsToPolymorphicBlogModelSerializer.config.jsonapi_use_foreign_key_on_belongs_to_relationship = original_option + end + expected = { data: { id: '1', type: 'posts', relationships: { blog: { data: nil } } } } + + assert_equal expected, actual + end + class ExternalBlog < Blog attributes :external_id end