Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.save() on existing model causes POST instead of PUT

Tags:

backbone.js

I'm having some trouble saving changes to individual models in a collection. Models that have been loaded (via a collection .reset()) are issuing a POST (as if they were new) instead of the expected PUT.

Here's the approach I'm taking:

AppView

  • Loads the child collection via this.model.childcollection.reset(JSON DATA FROM SERVER);

  • In it's render function, creates a new childview for each item in the collection and renders it:

    render: function() {
            var el = this.el;
            this.model.childcollection.forEach(function(s) {
            var view = new ChildView({ model: s });
            el.append(view.render().el);
        });
        return this;
    },
    

ChildView

  • In one of its events it is changing some values of the underlying model and calling save:

    this.model.set(
            {
                ValueA: somevalue,
                ValueB: somevalue
            },
            {
                error: function() {
                    console.log("Error saving model");
                },
                success: function() {
                    console.log("Model change saved");
                }
            });
        this.model.save();
    

Observations:

  • POST (with no child id) is called instead of PUT (with child Id)
  • Child elements have Ids set

Can anyone tell me why this may be happening?

like image 739
UpTheCreek Avatar asked Sep 19 '11 15:09

UpTheCreek


People also ask

What happens if you use POST instead of put?

This method is idempotent. This method is not idempotent. PUT method is call when you have to modify a single resource, which is already a part of resource collection. POST method is call when you have to add a child resource under resources collection.

Can we use Put instead of get?

Can we use Put instead of get? The GET request returns current state, the PUT request changes the user selection. And then returns the new image as the result. Keeping the PUT data in URL is not REST like, yes.

Is put for update or create?

PUT is used to both create and update the state of a resource on the server.


1 Answers

backbone used the .id property (not attribute) of the model to determine whether it should put or post, as shown here in the source code: https://github.com/documentcloud/backbone/blob/master/backbone.js#L344-346

if it's doing a post when saving an existing model, this means the .id property wasn't loaded correctly. even if a call to model.get("id") returns the right result, a call to model.id must return the right result for it to know that this is not a new model.

be sure you're model's id attribute is called id, or if it's not, be sure to set the idAttribute on your model:

MyModel = Backbone.Model.extend({
  idAttribute: "myCustomId"
});
like image 182
Derick Bailey Avatar answered Sep 29 '22 12:09

Derick Bailey