在rails上的ruby中,是否可以使用find_each批处理对组进行求和查询?

时间:2010-05-19 12:18:41

标签: ruby-on-rails activerecord group-by sum

我正在从我的数据库加载数据,而我正在使用group by进行总和计算。

ElectricityReading.sum(:electricity_value, :group => "electricity_timestamp", :having => ["electricity_timestamp = '2010-02-14 23:30:00'"])

我的数据集非常大,超过100k,所以我想知道是否可以使用find_each批量处理以帮助处理内存开销。

我可以手动编写批量手动使用限制和偏移量,但我想在代码已经存在的情况下避免使用。

1 个答案:

答案 0 :(得分:0)

来自http://railsforum.com/viewtopic.php?pid=88198#p88198

@categories = Categories.find(:all, :joins => :animals,
                          :select => "categories.*, SUM(animals.weight) as weight_sum",
                          :group => "categories.id")
# ATTENTION: weight_sum is now a temporary attribute of the categories returned!
# and the animals are NOT eager-loaded`
<% @categories.each do |c| %>
  Category: <%= c.name %><br />
  Sum of Weight in this category: <%= c.weight_sum %><br />
<% end %>

它不是ActiveRecord.sum,但它应该可以解决问题。