mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-22 22:06:50 +00:00
Don't include empty polymoprhic associations
Take this serializer:
class TodoSerializer < ActiveModel::Serializer
root :todo, :include => true
has_one :reference, :polymorphic => true
end
A nil reference would generate this JSON:
{
"todo": { "reference": null },
"nil_classes": []
}
This commit prevents the `nil_classes` key from being added when
serializing and including nil polymoprhic associations.
This commit is contained in:
parent
486d282922
commit
6f3b250dc9
@ -194,6 +194,10 @@ module ActiveModel
|
||||
option(:include, source_serializer._root_embed)
|
||||
end
|
||||
|
||||
def embeddable?
|
||||
!associated_object.nil?
|
||||
end
|
||||
|
||||
protected
|
||||
|
||||
def find_serializable(object)
|
||||
@ -228,6 +232,14 @@ module ActiveModel
|
||||
end
|
||||
|
||||
class HasOne < Config #:nodoc:
|
||||
def embeddable?
|
||||
if polymorphic? && associated_object.nil?
|
||||
false
|
||||
else
|
||||
true
|
||||
end
|
||||
end
|
||||
|
||||
def polymorphic?
|
||||
option :polymorphic
|
||||
end
|
||||
@ -516,7 +528,7 @@ module ActiveModel
|
||||
|
||||
if association.embed_in_root? && hash.nil?
|
||||
raise IncludeError.new(self.class, association.name)
|
||||
elsif association.embed_in_root?
|
||||
elsif association.embed_in_root? && association.embeddable?
|
||||
merge_association hash, association.root, association.serialize_many, unique_values
|
||||
end
|
||||
elsif association.embed_objects?
|
||||
|
||||
@ -1244,4 +1244,24 @@ class SerializerTest < ActiveModel::TestCase
|
||||
smoothie.as_json
|
||||
end
|
||||
end
|
||||
|
||||
def tests_includes_does_not_include_nil_polymoprhic_associations
|
||||
post_serializer = Class.new(ActiveModel::Serializer) do
|
||||
root :post
|
||||
embed :ids, :include => true
|
||||
has_one :author, :polymorphic => true
|
||||
attributes :title
|
||||
end
|
||||
|
||||
post = Post.new(:title => 'Foo')
|
||||
|
||||
actual = post_serializer.new(post).as_json
|
||||
|
||||
assert_equal({
|
||||
:post => {
|
||||
:title => 'Foo',
|
||||
:author => nil
|
||||
}
|
||||
}, actual)
|
||||
end
|
||||
end
|
||||
|
||||
Loading…
Reference in New Issue
Block a user