坚持使用嵌入式记录的余烬模型

时间:2014-10-07 06:51:03

标签: javascript ember.js ember-data

我有以下的ember模型:

App.Location = DS.Model.extend({
    street: DS.attr('string'),
    city: DS.attr('string'),
    area: DS.attr('string'),
    lat: DS.attr('string'),
    lng: DS.attr('string'),
    report: DS.belongsTo('report', {embedded: 'always'})
});

App.Report = DS.Model.extend({
    title: DS.attr('string'),
    description: DS.attr('string'),
    reg_num: DS.attr('string'),
    location_str: DS.attr('string'),
    location: DS.belongsTo('location', {embedded: 'always'})
});

App.ReportController中,当我尝试保存报表时,我还想在请求有效负载中嵌入位置对象。到目前为止,我尝试了以下代码:

App.ReportController = Ember.ObjectController.extend({
    actions: {
        saveReport: function(record) {
            var self = this,
                report = this.get('model'),
                location = this.store.createRecord('location', {
                               lat: this.get('lat'),
                               lng: this.get('lng')
                           });
                report.set('location', location);
                report.save().then(function (result) {
                    self.transitionToRoute('list');
                });
            }
        }
    }
});

但是在请求中,有效负载位置始终为location: null

如何将location添加到请求有效负载?

2 个答案:

答案 0 :(得分:1)

也许我错过了一些东西,但我知道处理嵌入式记录的两种不同方式(ember-data> = 1.0.0-beta):

  1. Rewriting DS.Adapter's methods:serialize / extract * / normalize和其他, - 以Ember可以使用的方式设置JSON有效负载。
  2. 使用DS.EmbeddedRecordsMixin配置DS.Serializer。
  3. 由于default DS.Serializer's behavior with serializing relationships,我可以假设您获得location: null:Ember期望id属性中的belongTo值和hasMany属性中的ID列表。 LocationModel在创建之后和保存到服务器数据库之前没有id。当默认序列化程序尝试在保存ReportModel附加新创建的LocationModel时形成传出json有效内容时,它会获得LocationModelnull)的ID并将该ID放入{{ 1}}属性。

答案 1 :(得分:0)

将复合JavaScript对象放在有效载荷中不应该是火箭科学,我希望有一种不太复杂的方法来实现这一点。

确保没有为这两种关系定义belongsTo,因为最终会出现堆栈溢出:

App.Location = DS.Model.extend({
    street: DS.attr('string'),
    city: DS.attr('string'),
    area: DS.attr('string'),
    lat: DS.attr('string'),
    lng: DS.attr('string')
});

App.Report = DS.Model.extend({
    title: DS.attr('string'),
    description: DS.attr('string'),
    reg_num: DS.attr('string'),
    location_str: DS.attr('string'),
    location: DS.belongsTo('location', {embedded: 'always'})
});

我必须配置PostSerializer并覆盖serializeBelongsTo以使其工作

App.PostSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
    attrs: {
        location: {embedded: 'always'},
        report: {embedded: 'always'}
    }
});

DS.JSONSerializer.reopen({
    serializeBelongsTo: function(record, json, relationship) {
        var key = relationship.key,
            belongsToRecord = Ember.get(record, key);

        if (relationship.options.embedded === 'always') {
            json[key] = belongsToRecord.serialize();
        } else {
            return this._super(record, json, relationship);
        }
    }
});
相关问题