2013-10-11 61 views
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> 

請幫助我,謝謝

+1

不錯的嘗試,但...沒有。 – zeantsoi

+0

@zeantsoi,你讓我的一天 –

回答

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 
+0

謝謝q這麼多的作品..但我不想跳過只回答問題。如果用戶訪問該問題,並不回答它不應該在左邊隨機 –

+0

拉賈,很好,你得到它的工作。是的,您可以根據自己的喜好輕鬆定義規則。 –