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:
twinturbo 2012-07-16 15:08:01 +02:00
parent 486d282922
commit 6f3b250dc9
2 changed files with 33 additions and 1 deletions

View File

@ -194,6 +194,10 @@ module ActiveModel
option(:include, source_serializer._root_embed) option(:include, source_serializer._root_embed)
end end
def embeddable?
!associated_object.nil?
end
protected protected
def find_serializable(object) def find_serializable(object)
@ -228,6 +232,14 @@ module ActiveModel
end end
class HasOne < Config #:nodoc: class HasOne < Config #:nodoc:
def embeddable?
if polymorphic? && associated_object.nil?
false
else
true
end
end
def polymorphic? def polymorphic?
option :polymorphic option :polymorphic
end end
@ -516,7 +528,7 @@ module ActiveModel
if association.embed_in_root? && hash.nil? if association.embed_in_root? && hash.nil?
raise IncludeError.new(self.class, association.name) 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 merge_association hash, association.root, association.serialize_many, unique_values
end end
elsif association.embed_objects? elsif association.embed_objects?

View File

@ -1244,4 +1244,24 @@ class SerializerTest < ActiveModel::TestCase
smoothie.as_json smoothie.as_json
end end
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 end