我有两种型号:
Question = DS.Model.extend
answers: DS.hasMany("answer")
Answer = DS.Model.extend
question: DS.belongsTo("question")
json提供嵌入问题中的答案:
"questions": [{
"id":"1.04"
"text":"What is the position or title of the 1% who is being protested against?",
"answers":[
{
"text":"City mayor",
"id":"1.04.02"
},
{
"text":"City council member",
"id":"1.04.03"
},
{
"text":"CEO of some company",
"id":"1.04.01"
}
]
}]
当我调用question.get('answers')
时,Ember返回预期的答案数组。但是,如果我调用answer.get('question')
,则会得到null。知道为什么会发生这种事吗?
我认为你需要告诉Ember你的关系将被嵌入,这是这样做的。
Question = DS.Model.extend
answers: DS.hasMany("answer", embedded: 'always')
Answer = DS.Model.extend
question: DS.belongsTo("question", embedded: 'always')
话虽如此,您可能需要重新思考您的json结构,嵌入的记录会引起很多重复。
Ember期待着以下的开箱即用。
{
"questions": [
{
"id": "1.04"
"text": "What is the position or title of the 1% who is being protested against?"
"answer_ids": ["1.04.02", "1.04.03", "1.04.01"]
}
],
"answers": [
{
"text": "City mayor",
"id": "1.04.02",
"question_id": "1.04"
},
{
"text": "City council member",
"id": "1.04.03",
"question_id": "1.04"
},
{
"text": "CEO of some company",
"id": "1.04.01",
"question_id": "1.04"
}
]
}
假设您的question.get('answers')
可以工作,您只需要升级到Ember Data beta 10,它增加了对双方关系的支持。