Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix empty belongs_to with polymorphic serialization error #2433

Open
wants to merge 1 commit into
base: 0-10-stable
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
35 changes: 35 additions & 0 deletions test/serializers/associations_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down