Skip to content

Exclude id in serialized payload when nil. #76

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
May 20, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion lib/jsonapi-serializers/serializer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -359,10 +359,15 @@ def self.serialize_primary(object, options = {})

serializer = serializer_class.new(object, options)
data = {
'id' => serializer.id.to_s,
'type' => serializer.type.to_s,
}

# "The id member is not required when the resource object originates at the client
# and represents a new resource to be created on the server."
# http://jsonapi.org/format/#document-resource-objects
# We'll assume that if the id is blank, it means the resource is to be created.
data['id'] = serializer.id.to_s if serializer.id && !serializer.id.empty?

# Merge in optional top-level members if they are non-nil.
# http://jsonapi.org/format/#document-structure-resource-objects
# Call the methods once now to avoid calling them twice when evaluating the if's below.
Expand Down
16 changes: 16 additions & 0 deletions spec/serializer_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,22 @@ def serialize_primary(object, options = {})
},
})
end
it 'does not include id when it is nil' do
post = create(:post)
post.id = nil
primary_data = serialize_primary(post, {serializer: MyApp::PostSerializerWithoutLinks})
expect(primary_data).to eq({
'type' => 'posts',
'attributes' => {
'title' => 'Title for Post 1',
'long-content' => 'Body for Post 1',
},
'relationships' => {
'author' => {},
'long-comments' => {},
},
})
end
it 'serializes object when multiple attributes are declared once' do
post = create(:post)
primary_data = serialize_primary(post, {serializer: MyApp::MultipleAttributesSerializer})
Expand Down