编辑:这是错误的原因是因为即使它与submitted_answer
匹配,我也会继续迭代第一个answer
。不过,我仍然不知道如何解决这个问题。
这表明多项选择测验中用户的哪些答案是正确的还是错误的。 @quiz
此处指的是has_many Questions which
has_many Answers. @submitted_quiz refers to the model
已提交测验, which
has_many submitted_answers
. My plan is to compare
submitted_answers to the actual answers (found by
@ quiz的用户模型测验.question.answer),并向用户显示他们错误或正确的答案。这是代码:
<% @quiz.questions.each do |question| %>
<li> <%= question.content %> </li>
<% question.answers.each do |answer| %>
<% @submitted_quiz.submitted_answers.each do |submitted_answer| %>
<% if(submitted_answer.content == answer.content && submitted_answer.question.id == answer.question.id && submitted_answer.got_correct) %>
<li><span class ='correct-answer'><%= answer.content %> CORRECT </span></li>
<% break %>
<% elsif(submitted_answer.content == answer.content && submitted_answer.question.id == answer.question.id && submitted_answer.got_incorrect) %>
<li><span class ='incorrect-answer'><%= answer.content %> INCORRECT</span></li>
<% break %>
<% else %>
<li><span class ='normal-answer'> <%= answer.content %> NORMAL</span></li>
<% break %>
<% end # if statement%>
<% end # submitted_answers.each do%>
<% end # question.answers.each do |answer|%>
<% end # @quiz.questions.each do %>
</ol>
这适用于question
的第一个quiz.questions
。正确标记正确答案并正确标记错误答案。但是,在第二个(以及之后的每个问题)上没有任何标记正确或不正确。例如,如果正常输出应该是(用户得到两个问题):
Q1
Answer 1 CORRECT
Answer 2 NORMAL
Answer 3 NORMAL
Answer 4 NORMAL
Q2
Answer 1 CORRECT
Answer 2 NORMAL
Answer 3 NORMAL
Answer 4 NORMAL
实际输出为:
Q1
Answer 1 CORRECT
Answer 2 NORMAL
Answer 3 NORMAL
Answer 4 NORMAL
Q2
Answer 1 NORMAL
Answer 2 NORMAL
Answer 3 NORMAL
Answer 4 NORMAL
如果我删除else
语句,输出就会成为我的期望:
Q1
Answer 1 CORRECT
Q2
Answer 1 CORRECT.
但后来我无法在每个问题中显示所有答案。
我已经被困在这一天了。为什么会这样?
答案 0 :(得分:1)
尝试这样的事情:
<% @quiz.questions.each do |question| %>
<li> <%= question.content %> </li>
# In submitted quiz table, every submission must store question and answer ids.
<% submitted_answer = @submitted_quiz.submitted_answers.find_by(question_id: question.id) %>
# Every question record stores answer ids along with correct_answer id.
<% correct_answer_id = question.correct_answer %>
<% question.answers.each do |answer| %>
<% if answer.id == submitted_answer.answer_id && answer.id == correct_answer_id %>
<li><span class ='correct-answer'><%= answer.content %> CORRECT </span></li>
<% elsif answer.id == submitted_answer.answer_id && answer.id != correct_answer_id %>
<li><span class ='incorrect-answer'><%= answer.content %> INCORRECT</span></li>
<% else %>
<li><span class ='normal-answer'> <%= answer.content %> NORMAL</span></li>
<% end %>
<% end %>
<% end %>