How do I include linked relationships when serializing a model?

Update: The issue I’m seeing is due to the fact that model#serialize doesn’t include relationships defined with links. I’m looking for a safe way to include that link-based relationships in the serialized output so that after deserialization Ember knows how to fetch the relationships. Please see the latest update below.


For performance reasons, I load one record from local storage via pushPayload. This record has both sync and async relationships, and all of the relationships are null after the pushPayload call, and calling record.get('relationship-key') will not cause them to be loaded. In order for them to work again, I need to call rel[details=Summary]This text will be hidden[/details]oad prior to get.

Is there a way to reset these relationships without re-fetching the record? (At least the async relationships?) I want the record’s state to be the same as it would be after it’s freshly loaded.~

Push payload user adapter serializers to deserialize what you pass it to a DS model. When you stored your model in local storage have you serialized into de format your adapter is expecting relationships?

For JSONAPI it would we:

...
'relationships': {
  'related-obj': {
     'data': {
         'id': 1,
         'type': 'your-model',
     }
  }
}
...

I’m calling model.serialize({ includeId: true }), and the output is:

{
    data: {
        id: #,
        type: 'type',
        attributes: {
            /* every attribute */
        }
    }
}

It does not include any relationships at all. I would expect that async relationships would be retrievable with model.get('relationship-key') but they aren’t until after model.reload() is called.

I was wrong about the relationships included. It turns out that relationships expressed with links are not included but that relationships expressed with data are. The issue I was seeing is that after the call to pushPayload Ember has no idea how to fetch the relationships because no links are included.

I couldn’t figure out a safe way to modify the serialization to include these links, but adding this function to my model definition works:

  serializeWithLinks: function () {
    var obj = this.serialize({ includeId: true });
    var rels = this._internalModel._relationships.initializedRelationships;
    _.each(_.keys(rels), (key) => {
      if (rels[key].isAsync && rels[key].link) {
        obj.data.relationships[key.underscore()] = {
          links: {
            related: rels[key].link,
          },
        };
      }
    });
    return obj;
  },

What is the correct way to figure out the link for a relationship when serializing? It doesn’t look like that information is accessible when overriding JSONAPISerializer#serializeHasMany/serializeBelongsTo.