Ember RESTAdapter-模型中的hasMany关系-如何使用POST发送空数组? [英] Ember RESTAdapter - hasMany relationship in model - how to send empty array with POST?

查看:86
本文介绍了Ember RESTAdapter-模型中的hasMany关系-如何使用POST发送空数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ember noob在这里-

Ember noob here -

我有两个模型具有如下所示的 hasMany 关系-

I have two models with a hasMany relationship like below -

var Season = DS.Model.extend({
    name: DS.attr('string'),
    periods: DS.hasMany('period', {
        async: false
    })
});

var Period = DS.Model.extend({
    from: DS.attr('date'),
    to: DS.attr('date'),
    season: DS.belongsTo('season')
});

一个季节可以不存在任何时期-
这就是我创建季节记录并保存-

A Season can exist without any Periods - This is how I create a Season record and save --

        var season = this.store.createRecord('season', {
            name: name
        });

        season.save().then(function(season){
                   /* season saved */
        });

POST请求有效负载如下所示-

The POST request payload looks like this --

   {
    "season" : {
         "name" : "test"
     }
   }

但是后端API期望有效负载是这样的-带有空的句点数组

But the backend API expects the payload to be like this -- with an empty periods array

    {
    "season" : {
         "name" : "test"
         "periods" : []
     }
   }

如何实现?

推荐答案

您需要通过修改序列化程序来更改ember发送给服务器的内容,您可以覆盖 SeasonSerializer 仅适用于该模型,或者 ApplicationSerializer 可以在整个应用中使用。

You'll need to change what ember is sending to your server by modifying the serializer, you can either override SeasonSerializer for just that model or ApplicationSerializer to do it app wide.

请参阅API文档的本部分 http://emberjs.com/api /data/classes/DS.RESTSerializer.html#method_serialize

see this section of the API docs http://emberjs.com/api/data/classes/DS.RESTSerializer.html#method_serialize

类似的东西:

App.SeasonSerializer = DS.RESTSerializer.extend({
  serialize: function(snapshot, options) {
    var json = this._super(snapshot, options);

    if(json.periods === undefined) {
      json.periods = [];
    }

    return json;
  }
});

这篇关于Ember RESTAdapter-模型中的hasMany关系-如何使用POST发送空数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆