2013-05-31 134 views
4

我有一些問題獲得Backbone來保存多個集合層。我有以下型號:使用backbone.js在模型中保存嵌套集合

var Question = Backbone.Model.extend({ 
     urlRoot: "/question" 
    }); 

    var QuestionList = Backbone.Collection.extend({ 
     model: Question, 
     url: "/question", 
     parse: function(response) { 
      return response.objects; 
     } 
    }); 

    var QuestionBank = Backbone.Model.extend({ 
     urlRoot: "/questionbank" 
    }); 

    var QuestionBankList = Backbone.Collection.extend({ 
     model:QuestionBank, 
     url: "/questionbank", 
     parse: function(response) { 
      return response.objects; 
     } 
    }); 

    var Answer = Backbone.Model.extend({ 
     urlRoot: "/answer" 
    }) 

    var AnswerList = Backbone.Collection.extend({ 
     model: Answer, 
     url: "/answer", 
     parse: function(response) { 
      return response.objects; 
     } 
    }); 

問題銀行有很多問題,而且問題有很多答案。 當我救我收藏的模型是正確的,但送出不包括收藏的第二個層次的JSON(答案):

{"active_question_bank": true, "id": 
"51a8c5d72ace7a458fd0d000", "question_bank_name": "New Q", "questions": 
[{"active_question": true, "answers": [], "difficulty": null, 
"id": "51a8d1be2ace7a458fd0d008", "question": "What is your favorite Color?", 
"question_is_and_type": false, "question_type": 1, "resource_uri": 
"/question/51a8d1be2ace7a458fd0d008", "tags": [""]}], "resource_uri": 
"/questionbank/51a8c5d72ace7a458fd0d000"} 

特別是它發出了一個空白的「答案」:[]每次。我對骨幹相對來說比較陌生,所以也許這是一項不可能完成的任務,但這個概念似乎相當微不足道。

回答

4

嘗試在以下模式中定義模型和集合,然後檢查發送到服務器的JSON。

var Answer = Backbone.Model.extend({ 
    urlRoot: "/answer", 
}); 

var AnswerCollection = Backbone.Collection.extend({ 
    model: Answer, 
    urlRoot: "/answer", 
}); 

// a question can contain many answers which can be accessed via AnswerList 
var Question = Backbone.Model.extend({ 
    urlRoot: "/question", 
    defaults: { 
     AnswerList: new AnswerCollection(), 
    }, 
    parse: function(response) { 
     response.AnswerList= new AnswerCollection(response.AnswerList); 
     return response; 
    } 
}); 

var QuestionCollection = Backbone.Collection.extend({ 
    model: Question, 
    url: "/question", 
}); 

// question-bank contains many questions which can be accessed via QuestionList 
var QuestionBank = Backbone.Model.extend({ 
    urlRoot: "/questionbank", 
    defaults: { 
     QuestionList: new QuestionCollection(), 
    }, 
    parse: function(response) { 
     response.QuestionList = new QuestionCollection(response.QuestionList); 
     return response; 
    } 
}); 
+0

這實際上很有幫助,雖然我發現主要問題是我使用Tastypie,而不是Backbone。我會將此標記爲答案,因爲這確實有效。 – JazzyWhit