如何使用ember-data进行此操作?
{"poll":{"id":1,"question":"lym features",
"choices":[{"id":1,"text":"Improve AI", "PollId":1},
{"id":2,"text":"Multiplayer","PollId":1},
{"id":3,"text":"Modern Art","PollId":1}]}}
这是我服务器的json响应。我需要使用ember数据RESTAdapter来解析它。
答案 0 :(得分:1)
我必须覆盖extractSingle
中的DS.RESTSerializer
方法。有关详细信息,请参阅代码中的emberjs链接。
// http://stackoverflow.com/questions/14320925/how-to-make-embedded-hasmany-relationships-work-with-ember-data
// http://emberjs.com/api/data/classes/DS.RESTSerializer.html#method_extractSingle
App.PollSerializer = DS.RESTSerializer.extend({
extractSingle: function(store, type, payload, id) {
var poll = payload.poll;
var choices = poll.choices;
delete poll.choices;
poll.choices = [];
choices.forEach(function(c) {
poll.choices.push(c.id);
});
payload = { choices: choices, poll: payload.poll };
return this._super(store, type, payload, id);
}
});
这会将我原来的结构变成标准形式。
注意:愚昧无知的傻瓜,有一种更简单的方法可以做到这一点,我是否有某种陷阱,请自我解释。
答案 1 :(得分:1)
您可以使用EmberData EmbeddedRecordsMixin http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html并设置choices
。