postgresql - In Active Record (Rails), how to select a sum of a column from a has_many relation with every parent record? -


considering model:

user:   id: int  valuable:   id: int   user_id: int   value: int 

user has many valuables.

now here's thing. want use activerecord select multiple users query, after want able see sum of valuables, without having n+1 queries.

so, want able this:

# @var ids [array] bunch of user ids. user.where(id: ids).each |u|    puts "user ##{u.id} has total value of #{u.total_value} end 

and should 1 (or max 2) queries , not instantiate valuables. tried playing around select('*, sum(valuables.value) total_value).joins(valuables), no luck. i'm using postgresql

if @ possible, happen automatically (e.g. using default_scope) , still want able use includes.

update: sorry haven't been clear this. (actually, did write it). do not want valuables instantiated. have postgresql calculation me.

update: mean is, want depend on postgresql's sum method total sum in resultset. thought effort in using select , group by made clear. don't want data or record objects valuables table part of result, because consumes memory , calculating fields using ruby uses cpu , takes long.

in raw sql want this:

select users.*, sum(valuable.value) values_sum users left outer join valuables on users.id = valuables.user_id group users.id 

so translate in activerecord query this:

user.select('users.*, sum(valuables.value) total_value')     .joins('left outer join valuables on users.id = valuables.user_id') 

note not selecting columns valuables.

[10] pry(main)> @users = user.select('users.*, sum(valuables.value) total_value').joins('left outer join valuables on users.id = valuables.user_id')    user load (1.4ms)  select users.*, sum(valuables.value) total_value "users" left outer join valuables on users.id = valuables.user_id => [#<user:0x007f96f7dff6e8   id: 8,   created_at: fri, 05 feb 2016 20:36:34 utc +00:00,   updated_at: fri, 05 feb 2016 20:36:34 utc +00:00>] [11] pry(main)> @users.map(&:total_value) => [6] [12] pry(main)>  

however "default_scope" , "i still want able use includes" requirements might little tall unless want manually load associations.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -