我有这些模特:
TravelClient.Tour = DS.Model.extend({
title: DS.attr('string'),
description: DS.attr('string'),
seats: DS.attr('number'),
takenSeats: DS.hasMany('TravelClient.TakenSeat', {embedded:'always'})
TakenSeats: function() {
console.log(this.get('takenSeats').toArray())
}.property('takenSeats')
});
TravelClient.TakenSeat = DS.Model.extend({
tour: DS.belongsTo('TravelClient.Tour'),
number: DS.attr('number')
});
JSON看起来像这样:
{
"tours": [
{
"id": "5110e8b5a8fefe71e0000197",
"title": "qui deserunt dolores",
"description": "Id velit nihil.",
"seats": 12,
"taken_seats": [
{
"id": "5110e8b5a8fefe71e0000196",
"number": "5"
},
{
"id": "5110e8b5a8feffffe0000196",
"number": "2"
}]
}
但是,当我在Tour模型的方法中console.log(this.get('takenSeats').toArray()
时,它返回Uncaught TypeError: Cannot call method '_create' of undefined
,因此,似乎takeSeats没有加载父模型。怎么了?
更新
将tour_id添加到JSON,但现在,当我想使用计算属性时:
freeSeats: function() {
var seats = this.get('seats');
var takenSeats = this.get('takenSeats');
if (takenSeats) {
return (seats - takenSeats.length);
}
else {
return seats;
}
}.property('seats', 'takenSeats')
takenSeats未定义。
更新2:
TravelClient.RESTSerializer = DS.RESTSerializer.extend({
init: function() {
this._super();
this.map('TravelClient.Tour',{
images:{embedded:'always'},
options:{embedded:'always'},
takenSeats:{embedded:'always'}
});
}
});
TravelClient.CUSTOMAdapter = DS.RESTAdapter.extend({
bulkCommit: false,
serializer: TravelClient.RESTSerializer.create(),
url: "http://192.168.1.27:3000",
buildURL: function(record, suffix) {
var s = this._super(record, suffix);
return s + ".json";
}
});
TravelClient.Store = DS.Store.extend({
revision: 11,
adapter: TravelClient.CUSTOMAdapter.create()
});
TravelClient.store = TravelClient.Store.create();
答案 0 :(得分:1)
TakenSeats
计算属性被视为一个类,因为它是大写的。嵌入式加载旁边必须进行不同的配置。像这样:当dirty
发生变化时,巡视对象变为takenseat
。
DS.RESTAdapter.map('TravelClient.Tour', {
takenSeats: { embedded: 'always' },
});
或者:这样巡演不会成为dirty
。
DS.RESTAdapter.map('TravelClient.Tour', {
takenSeats: { embedded: 'load' },
});
在初始化Store和Adapter之前执行此操作。这将使计算属性不必要。你可以tour.get('takenSeats')
;
哦,您不必再指定类型是否已嵌入。链接回taken_seats
的{{1}}数组中的ID需要被称为tour
。
tour_id
答案 1 :(得分:0)
我遇到了类似的问题。 ember-model不通过嵌套对象进行映射。
您的JSON输出当前包含嵌套在tours
根目录下的所有数据。
如果您有权访问API,那么我建议您尝试删除root,否则请考虑使用您的主要对象,然后从那里抓取所有嵌套对象。
而不是:
"tours": [{
"id": "5110e8b5a8fefe71e0000197",
"taken_seats": [{
"id": "5110e8b5a8fefe71e0000196",
"tour_id": "5110e8b5a8fefe71e0000197"
"number": "5"
}]
}]
让它看起来像这样:
[{
"id": "5110e8b5a8fefe71e0000197",
"taken_seats": [{
"id": "5110e8b5a8fefe71e0000196",
"tour_id": "5110e8b5a8fefe71e0000197"
"number": "5"
}]
}]
可能我的语法已关闭,但这个类似的想法对我有用。