serializeHasMany (snapshot, json, relationship)
Serializes hasMany
relationships when it is configured as embedded objects.
This example of a post model has many comments:
Post = DS.Model.extend({ title: DS.attr('string'), body: DS.attr('string'), comments: DS.hasMany('comment') }); Comment = DS.Model.extend({ body: DS.attr('string'), post: DS.belongsTo('post') });
Use a custom (type) serializer for the post model to configure embedded comments
app/serializers/post.js
import DS from 'ember-data; export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { comments: { embedded: 'always' } } })
A payload with an attribute configured for embedded records can serialize the records together under the root attribute's payload:
{ "post": { "id": "1" "title": "Rails is omakase", "body": "I want this for my ORM, I want that for my template language..." "comments": [{ "id": "1", "body": "Rails is unagi" }, { "id": "2", "body": "Omakase O_o" }] } }
The attrs options object can use more specific instruction for extracting and serializing. When serializing, an option to embed ids
, ids-and-types
or records
can be set. When extracting the only option is records
.
So { embedded: 'always' }
is shorthand for: { serialize: 'records', deserialize: 'records' }
To embed the ids
for a related object (using a hasMany relationship):
app/serializers/post.js
import DS from 'ember-data; export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { comments: { serialize: 'ids', deserialize: 'records' } } })
{ "post": { "id": "1" "title": "Rails is omakase", "body": "I want this for my ORM, I want that for my template language..." "comments": ["1", "2"] } }
To embed the relationship as a collection of objects with id
and type
keys, set ids-and-types
for the related object.
This is particularly useful for polymorphic relationships where records don't share the same table and the id
is not enough information.
By example having a user that has many pets:
User = DS.Model.extend({ name: DS.attr('string'), pets: DS.hasMany('pet', { polymorphic: true }) }); Pet = DS.Model.extend({ name: DS.attr('string'), }); Cat = Pet.extend({ // ... }); Parrot = Pet.extend({ // ... });
app/serializers/user.js
import DS from 'ember-data; export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { pets: { serialize: 'ids-and-types', deserialize: 'records' } } });
{ "user": { "id": "1" "name": "Bertin Osborne", "pets": [ { "id": "1", "type": "Cat" }, { "id": "1", "type": "Parrot"} ] } }
Parameters:
-
snapshot
DS.Snapshot
-
json
Object
-
relationship
Object
Please login to continue.