简体   繁体   中英

how to get Ember-Data RESTAdapter to send “hasMany” records to server

I'm using Ember-Data beta 3. My Ds.models are similar to the following:

App.Item = DS.Model.extend({
  itemName: DS.attr('string'),
  strategy: DS.belongsTo('strat')
});

App.Strat = DS.Model.extend({
    stratName: DS.attr('string'),
    items: DS.hasMany('item',{async:true})
});

Using Ember-data's RESTAdapter, I'm able to populate the model using data from my server. But when I tried to persist data back to the server, none of the "App.Item" records got sent. The JSON received by my server only contained "stratName." I used "this.get('model').save()" to trigger the send.

What am I doing wrong?

Is there a reason why you are using an async relationship between your models?

If you set them as {embedded: always}, you can easily override the serializeHasMany function to include all of your related model information

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);
    }
},

You aren't doing anything wrong, save only saves that particular record.

However, it should be sending up the ids of the associated items, is that not happening?

You got to overwrite serializeHasMany in your adapter and use this adapter for model or an application, here is a coffescript example:

App.LMSSerializer = App.ApplicationSerializer.extend

  serializeHasMany: (record, json, relationship) ->
    key = relationship.key
    jsonKey = Ember.String.singularize(key) + '_ids'

    json[jsonKey] = []

    record.get(key).forEach( (item) ->
      json[jsonKey].push(item.get('id'))
    )
    return json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM