我现在正在学习Ember Data,并遇到了一个问题,如果不写丑陋的代码就无法解决(这是我的项目,所以我有时间尽我所能)。问题是:
我有三个模型:Post、User和Comment。代码可以更好地描述我的意思;)
/* Post Model */
Blog.Post = DS.Model.extend({
title: DS.attr('string'),
text: DS.attr('string'),
postedAt: DS.attr('string', { defaultValue: new Date() }),
comments: DS.hasMany("comment", { async: true })
});
/* ==Post Model== */
/* User Model */
Blog.User = DS.Model.extend({
name: DS.attr('string'),
avatar: DS.attr('string'),
comments: DS.hasMany("comment", { async: true })
});
/* ==User Model== */
/* Comment Model */
Blog.Comment = DS.Model.extend({
title: DS.attr("string"),
text: DS.attr("string"),
user: DS.belongsTo("user", { async: true }),
post: DS.belongsTo("post", { async: true }),
postedAt: DS.attr("date", { defaultValue: new Date() })
});
/* ==Comment Model== */
/* Post Controller (bad variant and it doesn't work - too many redirects error) */
leaveComment: function () {
var controller = this,
user = controller.get('user'),
post = controller.get('model');
var comment = this.get('store').createRecord('comment', {
title: controller.get('commentTitle'),
text: controller.get('commentText'),
user: user,
post: post
});
comment.save().then(function (res) {
controller.setProperties({
commentTitle: "",
commentText : ""
});
user.get("comments").then(function (comments) {
comments.pushObject(comment);
user.save().then(function (ures) {
console.log(ures);
post.get("comments").then(function (comments) {
comments.pushObject(comment);
post.save().then(function (pres) {
console.log(pres)
}, function (err) {
console.log(err);
});
});
}, function (err) {
console.log(err);
})
});
}, function (err) {
console.log(err);
});
/* ==Post Controller== */
/* Post Route */
Blog.PostRoute = Ember.Route.extend({
setupController: function (controller, model) {
this._super(controller, model);
controller.setProperties({
user: this.modelFor('application')
});
},
model: function(params) {
return this.store.find('post', params["post_id"]);
}
});
/* ==Post Route== */
/* 2nd variant */
/* Post Controller */
leaveComment: function () {
var controller = this,
user = controller.get('user'),
post = controller.get('model');
var comment = this.get('store').createRecord('comment', {
title: controller.get('commentTitle'),
text: controller.get('commentText'),
user: user,
post: post
});
comment.save().then(function (res) {}, function(err) { console.log(err) });
/* ==Post Controller== */
/* Application.js */
Blog.CommentSerializer = DS.ActiveModelSerializer.extend(DS.EmbeddedRecordsMixin, {
primaryKey: function() {
return '_id';
}.property(),
attrs: {
user: { embedded: 'always' },//{serialize: 'id', deserialize: 'id'},
post: { embedded: 'always' }//{serialize: 'id', deserialize: 'id'}
}
});
/* ==Application.js== */
使用第二种方式进行保存时,我的预览数据中有用户/帖子ID而不是对象 - 可能我不知道如何正确使用它。如果您有类似的经验,请帮助我解决这个问题。
更新:
当我使用第一种方法发出请求时 - ERR:网络错误 - 重定向太多
当我使用第二种方法发出请求时:
1)似乎DS.ActiveModelSerializer根本不起作用 2)在请求中有user_id和post_id,而不是嵌入式对象,对我来说实际上并不意味着发送嵌入式对象或id,我关心的只是更新相关模型。 请查看屏幕截图以更好地了解。
![Request using 2nd variant](https://istack.dev59.com/z6nsu.webp)
注:我也在Google上搜索了很长时间,没有得到我的问题的答案,所以如果您不确定您的答案,请不要回答 - 谢谢理解。
经过数小时的苦痛后,我想到了这个。
//Controller
comments: function () {
return this.get('model.comments')
}.property('model.@each.comments'),
post: function () {
return this.get('model');
}.property('post'),
user: function () {
return this.get('user');
}.property('user'),
actions: {
leaveComment: function () {
var controller = this,
user = controller.get('user'),
post = controller.get('post');
var comment = this.get('store').createRecord('comment', {
text: controller.get('commentText'),
user: user,
post: post,
postedAt: new Date()
});
comment.save().then(function (comment_res) {
controller.get("comments").pushObject(comment_res);
post.save().then(function (post_res) {
controller.set("commentText", "");
}, function (err) {
console.log(err);
});
}, function (err) {
console.log(err);
});
}
}
Blog.CommentSerializer = DS.ActiveModelSerializer.extend(DS.EmbeddedRecordsMixin, {
primaryKey: function () {
return '_id';
}.property()//,
//attrs: {//{ embedded: 'always' },
// user: { embedded: 'always' }, //{serialize: 'id', deserialize: 'id'},
// post: { embedded: 'always' } //{serialize: 'id', deserialize: 'id'}
//} // <-this doesn't work :\
});
Blog.PostSerializer = DS.ActiveModelSerializer.extend({
primaryKey: function () {
return '_id';
}.property(),
serializeHasMany: function(record, json, relationship) {
var key = relationship.key;
var json_key = key.singularize().decamelize() + '_ids';
var relationshipType = DS.RelationshipChange.determineRelationshipType(
record.constructor, relationship);
if (relationshipType === 'manyToNone'
|| relationshipType === 'manyToMany'
|| relationshipType === 'manyToOne') {
json[json_key] = Ember.get(record, key).mapBy('id');
}
}// <- And this really works!
正如您所看到的,我只更新了一个相关的模型 - Post,由于出现了“Too-many redirections”错误,我无法更新User模型(我在Post和Comment之间有双向链接,在Comment中有与User的单向链接(Comment属于User),我无法获取具有User属性的评论)。目前为止这是不可能的。此外,我对DS.EmbeddedRecordMixin感到非常失望:( 我不会关闭这个话题直到找到我的问题的答案,谢谢你的帮助!
DS.EmbeddedRecordsMixin
。我认为通常使用默认的Ember Data行为更可取,考虑仅使用ID更新您的模型,如果不起作用,则使用DS.EmbeddedRecordsMixin
。 - Pooyan Khosravicomment.save()
行之前停止尝试,使用post.pushObject(comment)
来查看是否更新了post.get('comments')数组。 - Craicerjackuser.get('comments')
和post.get('comments')
是否会更新? - Craicerjack