【发布时间】:2014-02-19 03:24:11
【问题描述】:
//Setup:
Ember: 1.3.2
Handlebars: 1.3.0
jQuery: 2.0.0
-----------------
MongoDB (_id's, embedded data)
我一直在尝试建立这样的多对多关系:
//Model:
App.Post = DS.Model.extend({
title: DS.attr('string'),
content: DS.attr('string'),
links: DS.hasMany('App.Post'),
});
出于(希望)显而易见的原因,应将链接作为 id 嵌入。
经过几天的挖掘,我设法让应用通过 RESTAdapter 正确序列化并提交数据,我使用的代码如下所示:
//Controller:
App.PostController = Ember.ObjectController.extend({
actions: {
addRelated: function(related) {
var links = this.content.get('links').pushObject(related);
this.content.save();
}
}
});
//Store:
App.Store = DS.Store.extend({
revision: 12,
adapter: DS.RESTAdapter.extend({
url: '/admin/api',
serializer: DS.RESTSerializer.extend({
primaryKey: function(type) {
return '_id';
},
addHasMany: function(hash, record, key, relationship) {
if (/_ids$/.test(key)) {
hash[key] = [];
record.get(this.pluralize(key.replace(/_ids$/, ''))).forEach(function(post) {
hash[key].push(post.get('id'));
});
}
return hash;
}
})
});
});
从我可以收集的数据来看,序列化程序需要表单中的数据
{post: {...}, links: [{...},{...}]}
但由于链接是 post 类型,如果可能的话,我宁愿不创建整个 App.Links 模型。
那么我可以将链接映射到帖子吗?如
{post: {...}, posts: [{...},{...}]}
我尝试添加一个 deserializeHasMany,但在使用 App.Post.find() 时没有被调用
我猜我需要编写一个自定义提取函数来获取 link_ids 并从中提取帖子到记录中?
【问题讨论】:
标签: javascript rest ember.js ember-data