Reputation: 693
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?
Upvotes: 0
Views: 301
Reputation: 434835
If answers are just strings then you could use an array field:
class Question
include Mongoid::Document
#...
field :answers, :type => Array
end
If answers have some internal structure (perhaps you want to track when they were created or changed or whatever), then you could use embeds_many
and two models:
class Question
include Mongoid::Document
#...
embeds_many :answers
end
class Answer
include Mongoid::Document
#...
embedded_in :question
end
Either one will let you work with q.answers
in a natural list-like way so rendering such things is a simple matter of <% q.answers.each do |a| %>
and you could shuffle
the answers to display them in a random order.
Upvotes: 2
Reputation: 1166
If you want dynamically generated forms for nested models, I suggest following this RailsCast: http://railscasts.com/episodes/196-nested-model-form-part-1
The RailsCast method uses application helpers to dynamically generate the new objects.
I tend to prefer @mu's method of using jQuery to create form elements. The nice thing about Rails is that, when passing nested attributes, you can give it whatever index you want. And so I'll generate a new form with an index of, say, Time.now.to_s
and no ID parameter. And so my controller receives a parameter that looks like this:
{"question" => {"answers_attributes" => { "1234567" => { "description" => "New answer" } } } }
Upvotes: 0