gpt4 book ai didi

ember.js - Ember 删除 hasMany 关系中的记录

转载 作者:行者123 更新时间:2023-12-05 07:53:39 25 4
gpt4 key购买 nike

在 ember 中,有一种相当简单的方法可以在 hasMany 关系中创建和保存记录:

this.get('parent').createRecord({...});          // creates a child
this.get('parent').createRecord({...}); // creates a second child

this.get('parent').save().then(function(parent){ // persists parent
parent.get('children').save(); // persists all children
});

如果我们检查我们的网络流量,我们将看到两个 POST 请求——每个请求一个:

PATCH localhost:3000/parent/123
POST localhost:3000/children/
POST localhost:3000/children/

但是,没有等效的方法可以对 DELETE 执行相同的操作。假设我们通过单击按钮将子模型标记为删除:

deleteChild: function(child) {
// isDeleted -> false
child.deleteRecord();
// isDeleted -> true
}

我们可以立即调用 child.save(),这将触发 DELETE localhost:3000/children/1,但如果我想批量保存它们稍后和以前一样 (parent.get('children').save();),然后将发生以下情况:

PATCH localhost:3000/parent/123
PATCH localhost:3000/children/2

没有发送 DELETE,所以当我重新加载页面时,记录又回来了。如果我执行 parent.get('children').removeObject(child),也会出现同样的问题。

在我看来, parent 的 createRecord 应该有一个等价物,如下所示:

this.get('parent').deleteRecord(child);

但不存在这样的功能。

注意:我使用的是 ember 1.13、ember data 1.13 和 JSONAPIAdapter/Serializer

更新 2: Looks like they fixed this in ember data 2

更新:以下代码或多或少地模拟了所需的功能:

this.get('parent').save().then(function(parent){
parent.get('children').save().then(function(children){
children.canonicalState.forEach(function(child){
if(child.isDeleted()){
child.save();
}
});
});
});

有一些冗余的列表解析,但它会为每条记录生成正确的请求。请注意,canonicalState 不知道新记录。

最佳答案

this.get('parent').deleteRecord(child);

发送DELETE请求基本上是:

child.destroyRecord();

Which is part of Model API.它立即发送 DELETE 请求。

如果您想稍后批量删除记录,请为 JSONAPI 准备后端并实现处理 PATCH 请求作为 it is part of how JSONAPI works.

关于ember.js - Ember 删除 hasMany 关系中的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32378504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com