I’m trying to create a questionnaire app in Rails using Mongoid. I keep stumbling over the database setup because I’m new to things.
I want the users to be able to create questions with the possibility for varying numbers of answers. Some questions might have two possibilities: true, false. Some might have four or five possibilities.
So I’ve tried to create a question model and an answer model, then embed the answers in the question. I’ve tried a model with question:string answer-a:string answer-b:string answer-c:string and so on. But both approaches seem stupid and unwieldy.
Is there a way to create a model that allows someone to create a question field and an answer field, but such that the answer field can have multiples? So, create question, add an answer, and keep adding answers until they’ve finished their multiple choice?
If answers are just strings then you could use an array field:
If answers have some internal structure (perhaps you want to track when they were created or changed or whatever), then you could use
embeds_manyand two models:Either one will let you work with
q.answersin a natural list-like way so rendering such things is a simple matter of<% q.answers.each do |a| %>and you couldshufflethe answers to display them in a random order.