Udders
Udders

Reputation: 67

Model creates new row instead of being edited

I am working on app at moment, when I create a group the save function works great the model gets added to the collection, and saved to the database, however if I then want to edit the group I have just made, when I hit save the new model is created (and POST request) instead of the data being edited and a PUT request being fired. Here is my save function - is there any reason I am not firing PUT requests when editing an exsisting model?

GroupModalHeaderView.prototype.save = function(e) {
  var $collection, $this;
  if (e) {
    e.preventDefault();
  }

  $this = this;
  if (this.$("#group-name").val() !== "") {
    $collection = this.collection;
    if (this.model.isNew()) {
      this.collection.add(this.model);
    }
    return this.model.save({ name: this.$("#group-name").val()}, {
      async: false,
      wait: true,
      success: function() {
        var modelID = $this.model.get('id');

        return this.modal = new app.GroupModalView({
          model: $this.collection.get(modelID),
          collection: $this.collection
        });
      }
    });
  }

};

This is my model defaults,

Group.prototype.defaults = {
  user_id: "",
  name: "New Group",
  email: "",
  url: "",
  telephone: "",
  mobile: "",
  fax: "",
  people: ""
};

Here is the console.log of this.model before it is saved,

    Group {cid: "c116", attributes: Object, _changing: false, _previousAttributes:    Object, changed: Object…}
        _changing: false
        _events: Object
        _pending: false
        _previousAttributes: Object
        email: ""
        fax: ""
        mobile: ""
        name: "New Group"
        people: ""
        telephone: ""
        url: ""
        user_id: ""
        wait: true
        __proto__: Object
        attributes: Object
        changed: Object
        cid: "c116"
        collection: GroupCollection
        id: 189
        __proto__: ctor

Upvotes: 1

Views: 79

Answers (1)

Nishant Jani
Nishant Jani

Reputation: 1993

The reason Backbone.js is firing a POST request instead of PUT is because your model does not have a unique identifier id associated with it.If there is not id attribute associated with your model, Backbone.js will always fire a POST request to save a new entry to db.

From backbone's website :

save model.save([attributes], [options]) ... If the model isNew, the

save will be a "create" (HTTP POST), if the model already exists on the server, the save will be an "update" (HTTP PUT).

Read this SO question for more information.

Upvotes: 1

Related Questions