0

我已经建立了一个在线考试应用程序。我有一些模型,例如:

  • 问题有很多答案
  • 答案属于问题
  • 考试

我为用户构建了表格,可以使用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

4

1 回答 1

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

于 2012-12-23T13:22:22.963 回答