How to make embedded hasMany relationships work with ember data

前端 未结 4 1616
既然无缘
既然无缘 2020-11-27 13:51

I can\'t get embedded hasMany to work correctly with ember data.

I have something like this

App.Post = DS.Model.extend({
          


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 14:51

    Adding an update to this incase others come across this post and are having a hard time figuring out what works with the current version of ember-data.

    As of Ember Data 1.0.0.beta.7, you need to override the appropriate methods on the serializer. Here's an example:

    1) Reopen the serializer (credit to this post):

    DS.RESTSerializer.reopen({
      serializeHasMany: function(record, json, relationship) {
        var hasManyRecords, key;
        key = relationship.key;
        hasManyRecords = Ember.get(record, key);
        if (hasManyRecords && relationship.options.embedded === "always") {
          json[key] = [];
          hasManyRecords.forEach(function(item, index) {
            // use includeId: true if you want the id of each model on the hasMany relationship
            json[key].push(item.serialize({ includeId: true }));
          });
        } else {
          this._super(record, json, relationship);
        }
      }
    });
    

    2) Add the embedded: 'always' option to the relationship on the model:

    App.Post = DS.Model.extend({
      comments: DS.hasMany('comment', {
        embedded: 'always'
      })
    });
    

提交回复
热议问题