model.destroy()返回sinatra后端的错误

时间:2013-04-11 21:53:36

标签: backbone.js sinatra destroy

我在使用model.destroy方法在骨干网中正常工作时遇到了问题。这是我的功能

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;
},

该模型如下所示:

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.");
}

});

这就是我的sinatra中的路线。

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

我不知道为什么我会收到错误。

2 个答案:

答案 0 :(得分:0)

如果您遵循this answer

的建议
delete '/user_event/:session_id' do
  user_event = ProjectTimer.get(:session_id => params[:session_id])
  user_event.destroy
  halt 204
rescue => e
  # do something with the exception, maybe log it
  halt 500
  # or set status to 500 and re-raise
end

有关详情,请参阅Halting in the Sinatra docs

答案 1 :(得分:0)

我确实通过将dataType设置为“text”来使其正常工作。我发现Backbone.sync期望返回被删除对象的JSON以便成功。因此,如果我们将dataType更改为Text,那么它会超过JSON预期。这是我的最终代码

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;
},