2013-06-05 44 views
0

控制器搜索最小,最大和平均價格欄

def show 
     @product = Product.find(params[:id]) 

     respond_to do |format| 
      format.html # show.html.erb 
      format.json { render json: @product } 
     end 
end 

查看

<% @product.compoFathers.each do |compo| %> 
    <% compo.productSon.suppliers.each do |sonSuppl| %> 
     <%= sonSuppl.price %> 
    <% end %> 
<% end %> 

我找最小值,平均值和最高價格。

請謝謝。

回答

0

試試這個代碼片段: -

<% average = minimum = maximum = total_price = count = 0 %>  
<% @product.compoFathers.each do |compo| %> 
    <% compo.productSon.suppliers.each do |sonSuppl| %> 
     <%= sonSuppl.price %> 
     <% count +=1 
      total_price += sonSuppl.price 
      minimum = sonSuppl.price if minumum == 0 
      maximum = sonSuppl.price if minumum == 0     
      if (sonSuppl.price > minimum) 
       if (sonSuppl.price > maximum) 
        maximum = sonSuppl.price 
       end 
      else 
       minimum = sonSuppl.price  # Previously it is minumum - 
      end 
     %>    
    <% end %> 
<% end %>  
Average = <%=average = total_price/count %> 
Maximum = <%=maximum %> 
Minimum = <%=minumum %> 
+2

你真的在做視圖嗎? – apneadiving

+0

錯誤:未定義的局部變量或方法'最小' – fredhouse

+0

更新在該咒語中,PLZ交叉檢查它。如果執行代碼時出錯,請告訴我。 – Rubyist

1

你應該使用dedicated database queries

Product.average("price") 
Product.maximum("price") 
Product.minimum("price") 

的原因是:

  • 經過優化

  • 你可能遲早需要分頁,所以你不應該需要加載所有的數據來獲取這些信息

+0

將它們組合成單個查詢會更快,不是嗎? –

+0

這些查詢速度非常快,我懷疑你可以將它們合併爲一個。如果是這樣,我很好奇 – apneadiving

+0

如何同意,這就是爲什麼我的第一點(優化)不夠好,這是分頁問題進入遊戲的地方。 – apneadiving

相關問題