0

我创建了一个测验,并希望将其显示为每页一个随机数......例如,首先它获得随机数 question_id = 2,然后是 4,然后是 2 等等。我不想重复相同的问题时我在视图中单击下一步

这是我的控制器

def answer 
 @user = current_user
 @student = Student.find_by_admission_no(@user.username)
 @exam_group = ExamGroup.find(params[:exam_group_id])
 @answer = Answer.new
 n = Question.count
 @ans = random1 
end
def ans
 @user = current_user
 @student = Student.find_by_admission_no(@user.username)
 @exam_group = ExamGroup.find(params[:exam_group_id])
end
def create
 #@ans = Question.find_by_id(1)
 @answer = Answer.new(params[:ans])
 @answer.answer = params[:answer]
 #@answer.questions_id = @ans.id
 if @answer.save
   redirect_to :controller => 'answers', :action => 'final'
 end
end
def random1
 rand_id = (Question.count)
 rand_record = Question.first(:conditions => [ "id = ?", rand_id])
end
def random2
 if (c = Question.count) != 0
   Question.find(:first, :offset =>rand(c))
 end
end

当我在视图中单击下一步

 <div class = "main">
   <% form_for @answer do |f|%>
    <%= render :partial => 'answers/ans' %>  
   <% end %>
 </div>
 <div class="extender"></div>  

和答案/答案

<div class = "answers">

<div class = "y">
  <div class = "label_field_pair">
    <label for "questions">
      <%= @ans.id %> ) <%= @ans.ques %>
    </label>  
  </div> <br>
    <div class = "label_field_pair2">
      <label for "options">
        <div id = "option-1">
          <%= radio_button_tag "answer", "#{@ans.id}ans1"%><%= @ans.ans1  %>
        </div><br>
        <div id = "option-2">
          <%= radio_button_tag "answer", "#{@ans.id}ans2"%><%= @ans.ans2 %>
        </div><br>
        <div id = "option-3">
          <%= radio_button_tag "answer", "#{@ans.id}ans3"%><%= @ans.ans3 %>
        </div><br>
        <div id = "option-4">
          <%= radio_button_tag "answer", "#{@ans.id}ans4"%><%= @ans.ans4  %>
        </div><br>
      </label>

</div>
<%= link_to "Next", :partial =>"ans"%>

</div>  
</div>

请帮助我,谢谢

4

1 回答 1

0
# Model
class User < ActiveRecord::Base
  has_many :answers

  def answered_questions
    # Suppose answer belongs to both user and question, quite reasonable.
    answers.map { |a| a.question_id }
  end
end

# QuestionsController
class QuestionsController < ApplicationController

  def show
    # Show your first question as you like
  end

  def next
    @question = Question.where('id not in (?)',answered).offset(left_random).first
    render 'show'
  end

  private
  def answered
    @i ||= current_user.answered_questions
  end

  def left_random
    count = Question.count - answered.count
    rand(count)
  end
于 2013-10-11T19:17:17.780 回答