我已经建立了exams_helper.rb
两种方法在视图中使用重复的代码:消除在辅助模块
<% @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
我该怎么写这些方法更好?
好吧,我想我要改写我的代码更好。当我需要首先加载考试答案时,“Memoization”也可能是我正在寻找解决问题的方法。非常感谢。 – Thanh