backbone model POSTs when it should PUT with use of .save()

54 views Asked by At

So I have this model that gets populated via .fetch() my problem is. It will either always PUT, or always POST but never is .save() acting "smart".

The model is populated from a fetch, which if anything is returned from the fetch, its ever at most a single item, so running a collection for it is a bit abusive. Anyway.. I know that the my issue is in part related to my use of idAttribute if I use it, the .save() always does a PUT if I don't its always a POST.

my.Models.note = Backbone.Model.extend({
    idAttribute:'note',
    initialize: function (data) {
        this.user_id = data.user_id;
    },
    parse: function(response) {
        if (response.status == 'SUCCESS') {
            return response.data;
        }
    },

    url:function(data)
    {
        var url = '/notes/';
            url += '?user_id='+this.user_id;
        return url;
    }
});
2

There are 2 answers

0
Sunil Ajagekar On

Its depends on your data , you should have id attribute in your data fetched from server, when you call save then automatically it sends a PUT call.if id is null then it send a POST call

0
prototype On

Backbone uses the id attribute to determine if it's an existing resource (PUT) or a new resource (POST).

If you don't want to use the id attribute, you can override Backbone.Model.sync (rather than URL method) to specify the method that it should use:

my.Models.note = Backbone.Model.extend({
    idAttribute:'note',
    initialize: function (data) {
        this.user_id = data.user_id;
    },
    parse: function(response) {
        if (response.status == 'SUCCESS') {
            return response.data;
        }
    },
    sync: function(options) {
       $.ajax({ 
         type: 'PUT', 
         data: this.toJSON(),
         url:  '/notes/?user_id='+this.user_id, 
         success: options.success,
         error: options.error
       });
       return this;
    }
});