2
votes

In my Ember app, I have a nested hasMany relationships using ember-data like so workout->exercise->set.

My API has nested JSON instead of sideloaded JSON, so to fetch an existing workout I use store.find('workout', id) and override extractSingle.

My problem is when building a new workout I need to prepopulate it with exercises and sets based on a workout plan that a user is following. On the server side, I just have a /new controller action that prepopulates everything and renders a template.

Now that I'm moving to Ember I need the same functionality, but can't seem to make it work. The first thing I tried was to use Ember.$.getJSON to call a custom API endpoint in conjunction with pushPayload. This doesn't work however, because pushPayload bypasses extractSingle which means I can't convert my nested JSON into side-loaded JSON.

The prepopulation logic is very complicated so I'd prefer not to duplicated it client side and retrieve it from the API. Any other ideas on how I could accomplish this using ember-data?

1

1 Answers

0
votes

For anyone trying to load embedded relationships with EmberData, check out EmberData's EmbeddedRecordsMixin.

Using Ember-CLI, you will need to create a serializer for the model with embedded relationships and add the mixin in the serializer like this:

// app/serializers/my-example-model.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {

Then, declare an attrs hash and include each embedded relationship with a hash for each, like this:

    attrs: {
        conference: { embedded: 'always' },
        organizationType: { embedded: 'always' }
    }
});

In my example above, conference and organizationType are both embedded in the myExampleModel model for both serializing and deserializing. That means that when I use this serializer over a RESTful API, I will get the embedded objects and I need to put the embedded objects.

The EmbeddedRecordsMixin has several options regarding each relationship, as in you have separate settings for serializing and deserializing. you can specify ids, records, or neither. embedded: always is shorthand for:

{
  serialize: 'records',
  deserialize: 'records'
}

It's all documented here with better examples here:

http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html.