Ruby on rails 为什么我的RubyonRails数据库查询这么慢?
以下代码始终使用超过10秒的时间。我已经升级了服务器,但是没有用。我知道我有一些数据库设计问题,但我不能修改 我展示了不同时间范围内不同地点的某一类别产品的所有价格,因为每个地点的价格每15天变化一次 控制器Ruby on rails 为什么我的RubyonRails数据库查询这么慢?,ruby-on-rails,ruby-on-rails-3,activerecord,ruby-on-rails-3.1,Ruby On Rails,Ruby On Rails 3,Activerecord,Ruby On Rails 3.1,以下代码始终使用超过10秒的时间。我已经升级了服务器,但是没有用。我知道我有一些数据库设计问题,但我不能修改 我展示了不同时间范围内不同地点的某一类别产品的所有价格,因为每个地点的价格每15天变化一次 控制器 def prods_x_cat # This will load all the products of a category @products = Product.prods_x_cat(params[:id],:include => :raw_datas) @corte
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
产品目录js.erb
var jqxhr1 = $.ajax($("#loading_overlay .loading_message, #loading_overlay").fadeIn());
$('#datos').html("<%= escape_javascript render :partial=>'/shared/prods_x_cat'%>")
var jqxhr1=$.ajax($(“#加载_覆盖。加载_消息,#加载_覆盖”).fadeIn());
$(“#datos').html(“'/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>
SKU
平均的
模式
最低限度
最大限度
如果没有看到所有涉及的代码,这类问题几乎不可能回答。相反,我可以帮助你找出问题所在
有很好的工具可以找到性能问题所在(例如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
如果打印的结果表明时间被其他地方占用,那么开始在模板中执行类似的操作。专注于数据库调用。是的,我刚刚安装了NewRelic。问题在于对数据库的调用,我应该找到减少查询的方法,但我不知道如何做,也许我可以将查询保存在对象中并对其进行迭代。因为每次我迭代调用DB的对象时,我都会在日志中看到对数据库的调用