Search code examples
backbone.jssinatradestroy

model.destroy() returning errors with sinatra backend


I'm having an issue getting my model.destroy method to work properly in backbone. This is my function

deleteEvent: function(){
    var self = this;
    var check = confirm("Are you sure you want to remove record " + this.model.get("ticket_id"));
    if (check == true){
        this.model.id = this.model.get('session_id');
        this.model.destroy({
            wait: true,
            success: function(model, response, options){
                console.log(options);
                console.log(response);
                self.$el.remove();
            },
            error: function(model, xhr, response){
                console.log("ERROR:");
                console.log(model);
                console.log(xhr);
                console.log(response);
            }
        });
    }
    else return;
},

The model looks like this:

vkapp.EventRecordModel = Backbone.Model.extend({
urlRoot: '/user_event',
idAttribute:"_id",
defaults: {
    "ticket_id": '',
    "start": '',
    "end": ''
},
validate: function(attrib){ //This is only called when setting values for the model, not on instantiation
    if (attrib.ticket_id == null)
        alert("no ticket number");
    if (attrib.start == undefined)
        alert("no start time");
    if (attrib.end == null)
        alert("no end time");
    if (attrib.start > attrib.end)
        alert("start can't be before the end time.");
}

});

And this is what the route looks like in my sinatra.

delete '/user_event/:session_id' do
    user_event = ProjectTimer.get(:session_id => params[:session_id])
    user_event.destroy
end

I am not sure why I am getting an error return.


Solution

  • I did get this working properly however by setting the dataType to "text." I found that Backbone.sync expects JSON of the object deleted to be returned in order to be successful. So, if we change the dataType to Text it over-rides that JSON expectancy. This is my final code

    deleteEvent: function(){
        var self = this;
        var check = confirm("Are you sure you want to remove record " + this.model.get("ticket_id"));
        if (check == true){
            this.model.id = this.model.get('session_id');
            this.model.destroy({
                dataType: "text",
                wait: true,
                success: function(model, response, options){
                    self.$el.remove();
                },
                error: function(model, xhr, response){
                    console.log("ERROR:");
                    console.log(model);
                    console.log(xhr);
                    console.log(response);
                }
            });
        }
        else return;
    },