Is it possible in ruby ​​on rails 3 to get sums for multiple columns in one query?

I want to get the amounts for a dozen columns in a table.

# result will be {:a => 340.5, :b => 21.8, ... } # where :a has the sum of the :a column values # entries is an ActiveRecord model, eg ScoreCard.where(:user => user) def self.totals(entries) [:a, :b, :c, :d, :e, :f, :g, :h, :i, :j, :k, :m].inject({}) do |tv, col| tv[col] = entries.sum(col) tv end end 

Is there a way to do this in a single request? The above generates a dozen requests.

+4
source share
1 answer

You can do something with manually overriding select values ​​like this, resulting in a single query that returns all your amounts in the form of fields:

 sums = entries.select("sum(a) as a, sum(b) as b, ....").first tv[:a] = sums[:a] tv[:b] = sums[:b] # etc.... 
+5
source

All Articles