4

我在让 Backbone 保存多层集合时遇到一些问题。我有以下型号:

    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

1 回答 1

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;
    }
});
于 2013-06-10T06:20:41.010 回答