Backbone model.save() 导致 POST not PUT [英] Backbone model.save() is causing POST not PUT
问题描述
我有一个 Backbone 模型:
I have a Backbone model:
var User = Backbone.Model.extend({
idAttribute: '_id',
url: '/api/user',
defaults:
{ username: ''
}
});
我去拿了:
var user = new User();
user.fetch();
现在,作为我的一个视图中的 click
事件,我有这个:
Now, as an click
event in one of my views, I have this:
toggleSubscription: function () {
user.set('subscriptions', true);
user.save();
}
这会导致 POST 请求.但是,该记录已经存在于服务器上,并且由于我获取了它(并且模型实例具有 id
属性),我认为 Backbone 应该执行 PUT 而不是 POST.为什么它会改为执行 POST?
This causes a POST request. However, the record already exists on the server, and since I fetched it (and the model instance has an id
property), I thought that Backbone should do a PUT instead of a POST. Why might it be doing a POST instead?
推荐答案
尝试检查 user.isNew()
.
看起来您创建了一个没有 ID 的新模型,这就是它尝试在 Backbone.sync
期间添加它的原因.
Looks like you created a new model which does not have an ID, that's why it's trying to add it during Backbone.sync
.
更新:
以上是完全正确的.它执行 POST
因为它是一个新模型(这意味着它没有 id).在获取模型之前,您需要给它一个 id.在您的示例中:
Above is exactly true. It does POST
because it's a new model (which means, it does not have an id). Before you fetch a model, you need to give it an id. In your example:
var user = new User();
user.fetch();
user.save(); // in XHR console you see POST
var user = new User({ id: 123 });
user.fetch();
user.save(); // in XHR console you see PUT
这篇关于Backbone model.save() 导致 POST not PUT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!