4
votes

I was reading through Ember docs and some examples on working with Embedded Object like JSON in Ember.

I came across the EmbeddedRecordsMixin feature and saw that we can write code like below to tell it is embedded record.

import DS from 'ember-data';

export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    author: { embedded: 'always' },
  }
});

Qouting the below from Ember page

Note that this use of { embedded: 'always' } is unrelated to the { embedded: 'always' } that is defined as an option on DS.attr as part of defining a model while working with the ActiveModelSerializer. Nevertheless, using { embedded: 'always' } as an option to DS.attr is not a valid way to setup embedded records.

And i have also seen model written like this.

App.Child = DS.Model.extend({
  name: DS.attr('string'),
  toys: DS.hasMany('toy', {embedded: 'always'}),
});

Where child object has toys object embedded.

Going by the first example, can i write the child serailizer as below?

App.ChildSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    toys: {embedded: 'always'}
  }
});

Can someone help me understand the difference between these two {embedded: 'always'} and what to use when?

Thanks

1

1 Answers

1
votes

Short answer: yes you can and you should.

Well, as far as I know, ember (especialy ember-data) is build to work perfectly with a Rails backEnd.

Rails have a module called ActiveModelSerializer to serialize resources and their related attributes and relationships. Into this module, you can use an option embedded: 'always' to serialize the whole targeted relationship and not only the ids when your client ask for a ressource. If you use it Rails side (server), you can handle it Ember side (client) by putting this option into your model if you want your ember-data store to handle it easily. It's just an 'echo' to this ActiveModelSerializer module functionality.

On the other side, if for example you create/update an object with many relationships, there is 2 ways to deal with it. The first is to first save object's relationships and then, on success, save the object itself. The second is to send it at once to your server with the option {embedded: 'always'} into your model's serializer, into the relationship you want to send at the same time (embedded) at the object itself.

Ember probably encourage to use this into the serializer, because putting this into model seems only related to a specific Rails option, and it's not straightforward at all. Moreover, putting this into the serializer fulfill this role, with or without ActiveModelSerializer.

Hope it's clear for you, if not, let me know so I can edit this.