我已经建立了一个在线考试应用程序。我有一些模特:
我为用户构建了表单,可以使用form_tag
进行检查。目前,我使用此代码在视图中的中调整问题答案的顺序:
<% question.answers.shuffle.each do |answer| %>
...
<% end %>
使用上面的代码,每次显示考试时,它都有不同的答案顺序。现在我想存储答案的顺序,所以我可以稍后复习考试。我正在考虑创建另一个模型来存储订单,但我不知道如何从 shuffle 方法获取订单。
所以我想问一种方法来存储在考试中的答案顺序,这将有助于我在考试中使用正确的答案顺序来回答问题。有人可以给我一个想法或解决方案吗?
更新模型以存储用户的答案
class ExamAnswer
belongs_to :exam
belongs_to :question
belongs_to :answer
end
此模型包含列:exam_id,question_id,user_answer_id
答案 0 :(得分:0)
# in app/models/question.rb
def answers_ordered(current_user)
answers_ordered = question.answers.shuffle
exam_answer = self.exam_answers.where(:user_id => current_user.id, :question_id => self.id, :exam_id => self.exam_id).first
if exam_answer.nil?
exam_answer.user_id = current_user.id
exam_answer.question_id = self.id
exam_answer.exam_id = self.exam_id
end
exam_answer.order_answers = answers_ordered.map{&:id} # add .join(';') if your sgdb does not handle the Array type
exam_answer.save
answers_ordered
end
# in your app/models/exam_answer.rb
class ExamAnswer
belongs_to :user
belongs_to :exam
belongs_to :question
belongs_to :answer
# add the field order_answers as type Array or String, depending of your SGBD
end
# in your view
<% question.answers_ordered(current_user).each do |answer| %>
...
<% end %>
然后,当您需要订单时,可以通过question.exam_answer.order_answers
访问该订单。我想我会做这样的事情。在answers_ordered
方法中删除不需要的内容。