我已经建立了两种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
我怎样才能更好地编写这些方法?