Rails ActiveRecord query pluck select sum
I have a complex query that calculates the sum of the weight of an object's relational attribute (for PosgreSQL)
Object.joins(:object_traits).where(object_trait: {name: [list_of_names]}).select("sum(object_traits.weight) as sum_weight, #{other direct object traits}").group("#{other direct object traits}").order('weight_sum')
Ideally I would like to pry out the sum of the weights for each object
+3
source to share
1 answer
Since the argument pluck
actually replaces the SELECT clause in the generated query, you can accomplish this simply by a) moving the call .select()
to the end of the chain and b) changing it to .pluck()
. For example, in a quick demo app, the following works:
irb> User.group("name").order("SUM(age) DESC").pluck("name, SUM(age)")
(1.0ms) SELECT name, SUM(age) FROM "users" GROUP BY "users"."name" ORDER BY SUM(age) DESC
=> [["rob2", 13], ["rob4", 5], ["rob", 1]]
Any suggestions joins
or where
should work as well.
+4
source to share