Handle correctly null associations

null belongs_to associations are now serialized as nil instead
of raise an error during serialization.
This commit is contained in:
Guillermo Iguaran
2014-10-30 09:35:05 -05:00
parent baf3db1365
commit 19ac139880
12 changed files with 64 additions and 17 deletions

View File

@@ -7,9 +7,13 @@ module ActiveModel
class BelongsToTest < Minitest::Test
def setup
@post = Post.new(id: 42, title: 'New Post', body: 'Body')
@anonymous_post = Post.new(id: 43, title: 'Hello!!', body: 'Hello, world!!')
@comment = Comment.new(id: 1, body: 'ZOMG A COMMENT')
@post.comments = [@comment]
@anonymous_post.comments = []
@comment.post = @post
@post.author = @author
@anonymous_post.author = nil
@serializer = CommentSerializer.new(@comment)
@adapter = ActiveModel::Serializer::Adapter::Json.new(@serializer)
@@ -18,6 +22,13 @@ module ActiveModel
def test_includes_post
assert_equal({id: 42, title: 'New Post', body: 'Body'}, @adapter.serializable_hash[:post])
end
def test_include_nil_author
serializer = PostSerializer.new(@anonymous_post)
adapter = ActiveModel::Serializer::Adapter::Json.new(serializer)
assert_equal({title: "Hello!!", body: "Hello, world!!", id: 43, comments: [], author: nil}, adapter.serializable_hash)
end
end
end
end

View File

@@ -6,10 +6,13 @@ module ActiveModel
class Json
class Collection < Minitest::Test
def setup
@author = Author.new(id: 1, name: 'Steve K.')
@first_post = Post.new(id: 1, title: 'Hello!!', body: 'Hello, world!!')
@second_post = Post.new(id: 2, title: 'New Post', body: 'Body')
@first_post.comments = []
@second_post.comments = []
@first_post.author = @author
@second_post.author = @author
@serializer = ArraySerializer.new([@first_post, @second_post])
@adapter = ActiveModel::Serializer::Adapter::Json.new(@serializer)
@@ -17,8 +20,8 @@ module ActiveModel
def test_include_multiple_posts
assert_equal([
{title: "Hello!!", body: "Hello, world!!", id: 1, comments: []},
{title: "New Post", body: "Body", id: 2, comments: []}
{title: "Hello!!", body: "Hello, world!!", id: 1, comments: [], author: {id: 1, name: "Steve K."}},
{title: "New Post", body: "Body", id: 2, comments: [], author: {id: 1, name: "Steve K."}}
], @adapter.serializable_hash)
end
end

View File

@@ -6,10 +6,12 @@ module ActiveModel
class Json
class HasManyTestTest < Minitest::Test
def setup
@author = Author.new(id: 1, name: 'Steve K.')
@post = Post.new(title: 'New Post', body: 'Body')
@first_comment = Comment.new(id: 1, body: 'ZOMG A COMMENT')
@second_comment = Comment.new(id: 2, body: 'ZOMG ANOTHER COMMENT')
@post.comments = [@first_comment, @second_comment]
@post.author = @author
@first_comment.post = @post
@second_comment.post = @post