4
votes

I am having some issues getting Backbone to save multiple layers of collections. I have the following models:

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

A questionbank has many questions, and a question has many answers. When I save my collection the model is correct, but the JSON that is sent out does not include the second level of collection (the answers):

{"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"}

In particular it sends a blank "answers": [] every time. I'm relatively new to backbone, so perhaps this is an impossible task, but the concept seems fairly trivial.

1

1 Answers

4
votes

Try defining the models and collections in the following pattern and then check the JSON being sent to the server.

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