Skip to content

Commit

Permalink
Don't embed empty associations in root
Browse files Browse the repository at this point in the history
  • Loading branch information
Adrian Mugnolo and Santiago Pastorino authored and spastorino committed Jan 9, 2014
1 parent 3e510c8 commit cec7980
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/active_model/array_serializer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,9 @@ def serializable_object
def embedded_in_root_associations
@object.each_with_object({}) do |item, hash|
serializer_for(item).embedded_in_root_associations.each_pair do |type, objects|
if hash[type]
next if !objects || objects.flatten.empty?

if hash.has_key?(type)
hash[type].concat(objects).uniq!
else
hash[type] = objects
Expand Down
33 changes: 33 additions & 0 deletions test/unit/active_model/array_serializer/serialization_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,39 @@ def profile
ensure
UserSerializer._associations[:profile] = @old_association
end

def test_embed_object_in_root_for_has_one_association_with_all_nil_values
@association = UserSerializer._associations[:profile]
@old_association = @association.dup

@association.embed = :ids
@association.embed_in_root = true

@user1 = User.new({ name: 'User 1', email: 'email1@server.com' })
@user2 = User.new({ name: 'User 2', email: 'email2@server.com' })

class << @user1
def profile
nil
end
end

class << @user2
def profile
nil
end
end

@serializer = ArraySerializer.new([@user1, @user2], root: :users)
assert_equal({
users: [
{ name: "User 1", email: "email1@server.com", 'profile_id' => nil },
{ name: "User 2", email: "email2@server.com", 'profile_id' => nil }
]
}, @serializer.as_json)
ensure
UserSerializer._associations[:profile] = @old_association
end
end
end
end

0 comments on commit cec7980

Please sign in to comment.