2012-12-07 31 views
1

我正在Web上製作一個測試應用程序,用戶可以在其中看到一個檢查列表,標記所有適用的內容並根據他所選內容獲取結果。循環遍歷一個數組,並比較每個類別的值並返回最高分值

每一個問題都有一個類別和值,和ID喜歡拿到了最高分(添加所有值爲每個類別和回報最高)

類我已經有點成功的,下面的代碼我得到的所有回答問題的得分相加,不考慮每一個問題屬於哪個類別

 @test_session.answered_questions.each do |a| 
     if a.answer == 1 
      @theResult.score = @theResult.score + a.q_value 
     end  
     @theResult.save! 
     end 

的問題是複選框,所以如果answer == 1複選框被標記

問題是,類別的數量是動態的..

我有一個想法,我可以循環通過@test_session.answered_questions.category.each添加類別值的一些變量,並比較所有類別的分數已經計算出來但是,我再次有一個動態數量的變量比較

我覺得有一些地圖功能我應該爲此

UPDATE

這裏用的是我如何設置的問題類別屬性

<%= nested_form_for @personal_test do |f| %> 

    <div class="field"> 
    <%= f.label "Name" %> 
    <%= f.text_field :name %> 
    </div> 
    <div class="field"> 
    <%= f.label "Description" %> 
    <%= f.text_area :description %> 
    </div> 

    <div class="field"> 
<%= f.fields_for :questions do |ff| %> 
    <%= ff.label "Question" %> 
    <%= ff.text_field :question_text %> 

    <%= ff.label "Question value" %> 
    <%= ff.number_field :value %> 

    <%= ff.select :category, options_for_select(Category.all.collect {|p| [ p.name, p.id ] }, :selected => ff.object.category), :prompt => 'Category' %> 
    <% end %> 
<% end %> 

回答

1

我想你會想做這樣的事情。我在代碼中添加註釋以嘗試並解釋它。

#loop through all categories... 
@test_session.answered_questions.category.each do |c| 
    sum = 0 
    #loop through every questions in current category 
    c.answered_questions.each do |a| 
     if a.answer == 1 
     sum += a.q_value 
     end 
    end 
    #keep track of the highest score and category as we go along... 
    #we can forget about the rest 
    if @theResult.score.nil? or sum > @theResult.score 
     @theResult.score = sum 
     @theResult.category = c 
    end 
end 

#theResult now holds the category with the highest score 

@theResult.save! 
+0

是的,我相信這是正是我一直試圖做的感謝,但即時得到一個錯誤'answered_questions.category.each'是一個未定義的方法,它不是一個真正的方法,但一個字符串屬性,每個問題都有,生病讓我的帖子告訴你我是如何設置的 – Matti

+0

我將需要你的模型代碼來告訴你到底應該如何看待循環。評論告訴你你想要循環的東西,所以如果你不能自己想出你的模型代碼。 –

+0

以及我不認爲我的模型會幫助,因爲他們是非常空的除了attr_accessors,我明白你寫的代碼,它確實幫助了很多 - 但我認爲我的問題是'category'不是一個模型其屬性,所以我不能在你使用'Category.all.collect'的表單代碼中使用'.each'函數 – Matti

相關問題