0

以下代碼總是使用多於十秒。我已升級服務器,但它沒有幫助。我知道我有一些數據庫設計問題,但我無法修改它。爲什麼我的Ruby On Rails數據庫查詢速度太慢?

由於價格在每個地點每15天更改一次,因此我顯示的是同一類別產品的不同位置的所有價格也在不同時間範圍內。

控制器

def prods_x_cat 
# This will load all the products of a category 
@products = Product.prods_x_cat(params[:id],:include => :raw_datas) 
@cortes = RawData.cortes 
    respond_to do |format| 
    format.js { render :layout=>false} 
    end 
end 

prods_x_cat.js.erb

var jqxhr1 = $.ajax($("#loading_overlay .loading_message, #loading_overlay").fadeIn()); 
$('#datos').html("<%= escape_javascript render :partial=>'/shared/prods_x_cat'%>") 

視圖

<%@cortes.each do |c|%> 
    <a href="#<%=c.corte%>" class="round_top"><%=c.corte%></a> 
    <%end%> 
    <%@cortes.each do |c|%> 
    <%@fecha = c.corte_real%> 
    <div id="<%=c.corte%>" class="block no_padding"> 
    <table class="display datatable"> 
    <thead> 
    <tr> 
     <th>SKU</th> 
      <%Company.active.order('table_field ASC').each do |c|%> 
       <th><%=c.abbr%></th> 
      <%end%> 
     <th>Average</th> 
     <th>Mode</th> 
     <th>Minimum</th> 
     <th>Maximum</th> 
    </tr> 
    </thead> 
    <tbody> 
    <%@products.each do |p|%> 
    <tr class="gradeA"> 
    <td><%=p.name%></td> 
    <%p.raw_datas.where("product_id='#{p.id}' and corte_real='#{@fecha}'").each do |prd|%> 
     <td><%=prd.location1.to_f.round(2)%></td> 
     <td><%=prd.location2.to_f.round(2)%></td> 
     <td><%=prd.location3.to_f.round(2)%></td> 
     <td><%=prd.location4.to_f.round(2)%></td> 
     <td><%=prd.location5.to_f.round(2)%></td> 
     <td><%=prd.location6.to_f.round(2)%></td> 
     <td><%=prd.location7.to_f.round(2)%></td> 
     <td><%=prd.location8.to_f.round(2)%></td> 
     <td><%=prd.promedio.to_f.round(2)%></td> 
     <td><%=prd.moda%></td> 
     <td><%=prd.minimo.to_f.round(2)%></td> 
     <td><%=prd.maximo.to_f.round(2)%></td> 
    <%end%> 
    </tr> 
    <%end%> 
    </tbody> 
    </table> 
    </div> 
    <%end%> 
    </div> 

回答

0

這類問題的在沒有看到所有代碼的情況下回答幾乎是不可能的。相反,我可以幫你找出問題所在。

有很好的工具可以找到你的性能問題(例如ruby-prof),但如果你想以一種簡單的方式找到你的問題,只需使用Time.now。例如,你可以改變你的控制器動作是:

def prods_x_cat 
# This will load all the products of a category 
a1 = Time.now 
@products = Product.prods_x_cat(params[:id],:include => :raw_datas) 
b1 = Time.now 
p "Time for finding products: #{b1 - a1}" 
a2 = Time.now 
@cortes = RawData.cortes 
b2 = Time.now 
p "Time for finding cortes: #{b2 - a2}" 
respond_to do |format| 
    format.js { render :layout=>false} 
end 
end 

如果打印提示,花費時間在其他地方,開始做在你的模板類似的東西。專注於數據庫調用。

+0

yes剛剛安裝NewRelic的問題是在調用數據庫,操作系統我應該找到方法來做更少的查詢,但我不知道如何,也許如果我可以保存我的查詢在一個對象迭代它。因爲每次迭代已經調用數據庫的對象時,我都會在日誌中看到對數據庫的調用 –