Topic: storing 100 Questions and answers


I need to be able to have a form with questions and answers.

There are about 100 questions and accordingly also 100 answers.

Now..if I hardcode the questions in the rhtml like <label>s with the answers as input tags accordingly then I would have huge .rhtml files and maintainability would be really a problem because the questions can change..

the questions are like "how old are you?", "what are your plans for the next five years" etc. Now I could make those the names for my answer table but that would be really annoying referring to them..

Any ideas as what would be the best way to store the questions? The questions are also divided into sections(personal/future plans etc).

Last edited by brianj (2007-05-17 18:47:47)

Re: storing 100 Questions and answers

Alright, so questions have the following:

integer for question_id
string for question_text (optionally add in extra columns for localization here)
string for short_name (something human readable but short -- yourAge, firstCrushName, etc)
string for category

Now, to display your form, you do something like the following:

# I'd put this in a helper to keep massive code out of the RHTML.  Your mileage may vary
def group_questions

#I'm in your RHTML, building your forms!
<%= start_form_tag :action => 'create' %>
  <% group_questions.each do | category, questions | %>
    <h2>Question category: <%= category %></h2><br/>
    <% questions.each do |question| %>
      <label for="question_<%=question.short_name%>"><%=question.question_text%></label>
      <%= text_field "pick_an_object", "question_"+question.short_name>
    <% end %>
   <% end %>
<%= end_form_tag %>

With some trivial alterations you can make that into a partial (a good idea if you're going to use essentially the same form in the edit action as well).  Now all you have to do to add a new question is issue direct SQL to do it, use an interface, or just open up your console and write something like:

Question.create(:question_text => "What is the airspeed of an unladen swallow?", :short_name => "python", :category => "Kingship Trivia").save

Apologies if I botched some syntax here, this is live coding from memory and we all know how dangerous that is.

Edited to add:

Oh, a note about Answers

Answer << ActiveRecord::Base

  has_one :question
  belongs_to :user  #user has_many :answers
  #has a text field for the answer

Last edited by patio11 (2007-05-17 22:17:52)

Re: storing 100 Questions and answers

Thanks for your reply! good stuff.

Im wondering about the answers though.

How do I express that each text_field belongs to a answer object? How should the code in the controller be?

Re: storing 100 Questions and answers

never mind. I got it smile. I have to use fields_for