11

I have an object that's also saved in the server and I'm creating a Backbone model from that object.

But when I save the model, it's doing a PUT request, which is not what I want. How to tell Backbone that the data is already in the server without doing a fetch?

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
archmage
  • 1,101
  • 10
  • 10
  • Backbone maps update requests to PUT http://documentcloud.github.com/backbone/#Sync so what behavior do you expect? – nikoshr Apr 11 '12 at 16:41
  • I thought update requests were mapped to POST, but PUt was used to create a new item. – archmage Apr 11 '12 at 16:45
  • If someone wants to force a POST request, there are [multiple alternatives](http://stackoverflow.com/a/41091957/1218980). – Emile Bergeron Dec 12 '16 at 01:43

2 Answers2

19

Backbone determines the newness of a model by checking if an id is set :

isNew model.isNew()

Has this model been saved to the server yet? If the model does not yet have an id, it is considered to be new.

And when you save a model,

  • if it is new, a POST request will be emitted,
  • if it is an update (an id has been set), a PUT request will be sent

Backbone Sync documentation


And as noted by @JayC in the comments :

If there's an issue that the id can't literally be id, you can use idAttribute to say which is the "identity" or key field.

Community
  • 1
  • 1
nikoshr
  • 32,926
  • 33
  • 91
  • 105
  • 4
    Note, if there's an issue that the id can't literally be `id`, you can use idAttribute. http://documentcloud.github.com/backbone/#Model-idAttribute to say which is the "identity" or key field. – JayC Apr 11 '12 at 17:18
  • A question: I have a model which is new (no id), but it has other fields set in the front end. when I save the model, it's sending a PUT request. Shouldn't it send a POST request because there is no ID? – archmage Apr 11 '12 at 21:49
  • 2
    @archmage Strange, it should be a POST. Check this Fiddle http://jsfiddle.net/jq98Z/ , it reproduces the expected behavior. Maybe you overrode the default sync or the action mapping somewhere? – nikoshr Apr 12 '12 at 08:00
  • my model has a id even before saving it. but the isNew still works – akantoword Jun 03 '16 at 23:46
  • 1
    @jlei Check if you have an idAttribute set or an isNew override. If not, please post a question – nikoshr Jun 04 '16 at 06:23
-1

Adding my two cents here, hope it avoids some hair pulling I had to do.

Setting a model's id property directly via constructor to false or null won't do the trick, you have to actually remove it from memory via via delete

For example, I just struggled to copy attributes from one model type to another type as a new model:

copy = Trip.clone()
#doesn't unset the id attribute
schedule = new models.Schedule(_.extend(copy.attributes, {id:null, trip_id:id})
#does unset the id attribute
delete schedule.id
schedule.save null, success: =>
  # back from POST vs PUT   
  ...
benipsen
  • 493
  • 6
  • 12