坚持烬模型的嵌入式记录
我有以下烬型号:坚持烬模型的嵌入式记录
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
添加到请求负载?
也许我'失去了一些东西,但我知道处理的嵌入式记录两种不同的方式(烬数据> = 1.0.0-β):
- Rewriting DS.Adapter's methods:串行/提取* /规范和其他人, - 以Ember可以使用的方式设置JSON负载。
- 使用DS.EmbeddedRecordsMixin来配置DS.Serializer。
我可以假设你是因为default DS.Serializer's behavior with serializing relationships的location: null
:灰烬预计id
值belongTo
财产和ID列表中hasMany
属性。 LocationModel
在创建之后和保存到服务器数据库之前没有id。当默认序列化程序试图在保存ReportModel
并附加新创建的LocationModel
时形成传出json有效内容时,它将获取标识LocationModel
(null
)并将该标识置于location
属性中。
谢谢,我不得不重写DS.JSONSerializer并使用DS.EmbeddedRecordsMixin配置来实现此功能。我会发布完整的答案。 – 2014-10-08 05:45:27
将复合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);
}
}
});
什么版本的烬数据和你使用什么串行器? – Microfed 2014-10-07 10:06:05
DEBUG:Ember数据:1.0.0-beta.7.f87cba88 – 2014-10-07 18:11:43