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)
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?