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

@@ -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