不想在rails上的ruby中重复代码

时间:2013-10-11 18:22:57

标签: ruby-on-rails random render

我创建了一个测验,并希望在每个页面中随机显示该视图中的一个...例如,首先它获得随机数的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>  

和答案/ ans

<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 个答案:

答案 0 :(得分: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