where to get the record id when calling backbone.js destroy

Jason picture Jason · Jan 14, 2012 · Viewed 7.3k times · Source

I have some test code that i'm just trying to use to figure out backbone.js. when i call destroy on a model object backbone makes a DELETE request to my rest service. but, i can't see any ID indicating which record is being deleted in the request data, the querystring, body or anywhere.

my model has an id property and i've assigned it a value of 1. is there anything else that i have to do to make sure the id gets passed through the server? or is there some other way that i'm supposed to detect what record is being deleted?

Edit - Here's the relevant code:

var AccountModel = Backbone.Model.extend({
    url: 'Account/Update',
    id: null,
    username: ''
});

var accountM = new AccountModel({id: 1, username: 'test'});

accountM.destroy();

When I look at the debugger I see the AJAX request is made, it just looks like this:

Request URL:http://localhost/probli/Account/Update
Request Method:DELETE
Status Code:200 OK

There doens't seem to be an ID or anything and there's no post data. Am I doing anything wrong? Thanks.

Answer

soldier.moth picture soldier.moth · Jan 16, 2012

You should set the urlRoot attribute of your model then let Backbone handle constructing the DELETE url:

var AccountModel = Backbone.Model.extend({
    urlRoot: 'Account/Update',
    id: null,
    username: ''
});

This will cause the following request when accountM.destroy() is called:

Request URL:http://localhost/probli/Account/Update/1
Request Method:DELETE
Status Code:200 OK