Reputation: 383
I guess my problem is two-fold:
surveys/show.html.erb:
<ol>
<% @survey.questions.each do |question| %>
<li class = 'question'><%= question.content %>
<ul>
<% for answer in question.answers %>
<li class = 'answer'>
<%= answer.content %>
<%if answer.correct_answer == true %>
<span> <b>Correct Answer</b> </span>
<% else %>
<span> <b>Incorrect Answer</b></span>
<% end%>
</li>
<% end %>
</ul>
</li>
<% end %>
</ol>
What would the form equivalent look like?
Upvotes: 2
Views: 451
Reputation: 5623
Basically, I'd have a QuestionsController
and AnswersController
this is because I know there may be other things I want to do with a question and answer via HTTP later.
I'd also have a table for storing the answer, question and user, which you could call answered_questions
class AnsweredQuestion
belongs_to :user
belongs_to :question
belongs_to :answer
end
class User
has_many :answered_questions
end
class Question
has_many :answered_questions
end
class Answer
has_many :answered_questions
end
class Survey
has_many :questions
has_many :answered_questions, through: :questions
accepts_nested_attributes_for :answered_questions
end
class SurveysController
def answer_question
@survey = Survey.find(params[:id])
@survey.update(answer_question_params) # not sure this is best way here, need to research a better way to create the nested resources rather than update
end
private
def answer_question_params
params.require(:survey).permit(answered_questions_attributes: [:answer_id, :question_id, :user_id])
end
end
Then to allow your user select an answer, I'd have something like:
<ol>
<%= form_for @survey, url: survey_answer_questions_path do |f| %>
<% @survey.questions.each do |question| %>
<li class = 'question'><%= question.content %>
<ul>
<%= f.fields_for :answered_questions do |aq| %>
<%= aq.hidden_field :question, question.id %>
<%= aq.hidden_field :user, current_user.id %>
<% question.answers.each do |answer| %>
<%= aq.radio_button :answer, answer.id, answer.correct_answer %>
<%= aq.label :answer, answer.content %>
<% end %>
<% end %>
</ul>
</li>
<%= f.submit_button "Answer" %>
<% end %>
</ol>
I'm doing this on the fly, couldn't really test if these are all correct, but it shows a general overview/approach I would take.
Let me know if that helps.
Upvotes: 3