我已经开始使用ember数据了,我遇到了一些问题。如果我的成分的json结构是:
[
{
"name":"flax seed",
"retailer":"www.retailer.com",
"nutrient_info":[
{
"type":"vitamin A",
"amount":"50mg"
},
{
"type":"calcium",
"amount":"30mg"
}
]
},
{
"name":"soy milk",
"retailer":"www.retailer-two.com",
"nutrient_info":[
{
"type":"vitamin D",
"amount":"500mg"
},
{
"type":"niacin",
"amount":"5000mg"
}
]
},
{ other ingredients... }
]
我认为这是我定义模型的方式:
var attr = DS.attr,
hasMany = DS.hasMany,
belongsTo = DS.belongsTo
App.Ingredients = DS.Model.extend({
// id: attr('number'), // don't include id in model?
name: attr('string'),
retailer: attr('string'),
nutrientinfo: hasMany('nutrients')
})
App.Nutrients = DS.Model.extend({
type: attr('string'),
amount: attr('string'),
ingredient: belongsTo('ingredients')
})
服务器有效负载应该是什么样的,我是否需要自定义REST适配器?我是否需要在模型中定义成分id: attr()
?
赞赏澄清其中一些概念的任何帮助。
答案 0 :(得分:1)
通常模型定义是单数的(另外我将Nutrinfo更改为nutrient_info):
App.Ingredient = DS.Model.extend({
// id: attr('number'), // don't include id in model?
name: attr('string'),
retailer: attr('string'),
nutrient_info: hasMany('nutrient')
})
App.Nutrient = DS.Model.extend({
type: attr('string'),
amount: attr('string'),
ingredient: belongsTo('ingredient')
})
格式需要如下(从端点或使用序列化程序)
{
// Ingredient records
ingredients:[
{
id:1,
"name":"flax seed",
"retailer":"www.retailer.com",
"nutrient_info":[1,2]
},
{
id:2,
"name":"soy milk",
"retailer":"www.retailer-two.com",
"nutrient_info":[3,4]
},
{ other ingredients... }
],
// Nutrient records
nutrients: [
{
id:1,
"type":"vitamin A",
"amount":"50mg",
ingredient:1
},
{
id:2,
"type":"calcium",
"amount":"30mg",
ingredient:1
},
{
id:3,
"type":"vitamin D",
"amount":"500mg",
ingredient:2
},
{
id:4,
"type":"niacin",
"amount":"5000mg",
ingredient:2
}
]
}
这是一个使用序列化程序和你的json的例子,我必须手动分配id(尽管这是无效的,你应该发送id,或者使用UUID),但这应该给你一个如何使用序列化器的想法:
App.IngredientSerializer = DS.RESTSerializer.extend({
extractArray: function(store, type, payload, id, requestType) {
var ingredients = payload,
nutrientId = 0,
ingredientId = 0,
ids = [],
nutrients = [];
ingredients.forEach(function(ing) {
ing.id = ingredientId++;
var nInfo = ing.nutrient_info,
nIds = [];
nInfo.forEach(function(n){
n.id = nutrientId++;
n.ingredient = ing.id;
nIds.push(n.id);
nutrients.push(n);
});
ing.nutrient_info = nIds;
});
payload = {ingredients:ingredients, nutrients:nutrients};
return this._super(store, type, payload, id, requestType);
}
});