Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone destroy not sending params

I've got a backbone model that I'm trying to destroy, but no params are being sent with the request, so the server is returning a 'Delete 404 not found' error.

I'll admit my structure is a bit strange as I'm creating/destroying the items based on if they are in a list already or not.

var list_item = new MyApp.Models.ListItem({item_id: this.model.id, group_id: this.model.group_id});

    if($(e.currentTarget).hasClass('add')){

            list_item.save(list_item, { 
                success: function(response){
                     this.model.attributes.addedtolist_id = response.id
                     console.log(this.model);
                },
                error: function(){
                     alert('could not save item');
                }
           });
    } else if($(e.currentTarget).hasClass('remove')) {
         list_item.id=this.model.addedtolist_id;
         list_item.attributes.id = this.model.addedtolist_id;
         console.log(list_item);
         list_item.destroy({
             success: function(){
                alert('delete');
             },
             error: function(){
               alert('could not uncheck');
            }
   });
}

the console output for list_item before destroy is

_escapedAttributes: Object
_previousAttributes: Object
_setting: false
attributes: Object
 id: 2
 item_id: 66
 group_id: 64
__proto__: Object
cid: "c23"
id: 2
__proto__: q

but when I look at the headers sent with the delete request, I don't have any params being sent.

-----------------------update params being sent, 404 still being returned --------------

as per Yaroslav's recommendation, I've added a 'header' to the destroy method, but my rails controller is still returning a DELETE 404 not found error. I'm just trying to return the listitem to make sure i'm getting the right one before I destroy it.

My controller is

 def destroy
   listitem = Listitem.find(params[:id])
   return render :json => listitem
 end
like image 265
pedalpete Avatar asked Jun 15 '12 04:06

pedalpete


2 Answers

I'd guess that you're setting the url in the model to a string:

Backbone.Model.extend({
    url: '/list_items',
    //...
});

That will tell Backbone to use exactly /list_items as the URL for all actions. You should use a function:

url: function() { return '/list_items/' + encodeURIComponent(this.id) }

or use a string with urlRoot and let the default url function add the id:

urlRoot: '/list_items'
like image 196
mu is too short Avatar answered Oct 18 '22 07:10

mu is too short


What params are you expecting to be sent? Destroy makes just a http delete request by the url without body or any additional headers by default. The params argument is pased to the jquery ajax function, so you can specify headers there:

model.destroy({
...
    headers : {
        your_header : 123
    }
})
like image 37
Yaroslav Avatar answered Oct 18 '22 05:10

Yaroslav