The App Layout
I am building an App, where one can create surveys. Every survey has multiple questions. I am embedding the questions into the survey model (with embeds_many in Mongoid), so a survey may look like this:
{
"id": "4f300a68115eed1ddf000004",
"title": "Example Survey",
"questions":
[
{
"id": "4f300a68115eed1ddf00000a",
"title": "Please describe your experience with backbone.js",
"type": "textarea"
},
{
"title": "Do you like it?",
"id": "4f300a68115eed1ddf00000b",
"type": "radiobutton",
"options": ["Yes", "Yes, a lot!"]
}
]
}
Now, there is also a survey editor which consists of a SurveyView, which displays the survey and lists the questions. If I click on a single question, a QuestionView will pop up, where I can edit the question. And when I am satisfied with my survey and I click save, the SurveyModel will be sent to the server.
The problem
What is the best way to handle the embedded association?
If I pass survey.get("questions")[any_index] to the QuestionView, and the question gets changed, I have to manually search for the question.id in my model and update my model. This feels wrong.
If I create a QuestionsCollection in my SurveyModel (is this even possible?). Then I can do things like fetching a Question out of this collection by id, pass it to the view and when I change the model, everything will get updated automatically, but I have to specify an url in the collection, and backbone will send single questions to the server, if things get updated.
Any suggestion on how to do this the backbone way?
you can most certainly have a questionsCollection inside your SurveyModel.
but you are right on the question being seen as a single question (since every question should have his own ID, it might still be possible to know on the server which survey it belongs to…)
then there is the parsing of your json:
if you are building your collection’s and models manually you won’t have this issue, but if you would add your nested JSON it will not automatically create a sub collection to your model. you would need to specify such things in an overridden parse method.