控制器
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 :(得分:1)
您应该使用dedicated database queries:
Product.average("price")
Product.maximum("price")
Product.minimum("price")
原因是:
他们已经过优化
您可能迟早需要分页,因此您不需要加载所有数据来获取这些信息
答案 1 :(得分: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 %>