exams_helper.rb
ビューで使用する2 つのメソッドを組み込みました。
<% @topic_questions.each do |topic_question| %>
<tr>
<td><%= topic_question.topic.name %></td>
<td><%= correct_questions(@exam_result.exam_id, topic_question.topic_id) %></td>
<td><%= number_to_percentage(ratio(@exam_result.exam_id, topic_question.topic_id), precision: 0) %></td>
</tr>
<% end %>
トピックの正解数の計算方法:
def correct_questions(exam_id, topic_id)
total = ExamQuestion.where(exam_id: exam_id, topic_id: topic_id).count
correct = ExamQuestion.where(exam_id: exam_id, topic_id: topic_id, correct: true).count
correct.to_s + '/' + total.to_s
end
正解率の計算方法
def ratio(exam_id, topic_id)
total = ExamQuestion.where(exam_id: exam_id, topic_id: topic_id).count
correct = ExamQuestion.where(exam_id: exam_id, topic_id: topic_id, correct: true).count
ratio = (correct.to_f/total).round(2)*100
if ratio.nan?
ratio = 0
else
ratio
end
end
これらのコードが繰り返されます。
total = ExamQuestion.where(exam_id: exam_id, topic_id: topic_id).count
correct = ExamQuestion.where(exam_id: exam_id, topic_id: topic_id, correct: true).count
これらのメソッドをより適切に記述するにはどうすればよいですか?