Rails count of distinct values of a column of associated model in SQL -


i have in rails (4.1.8) app following models: event, user, box, eventboxmapping , following associations relevant question among them:

user has_many events; event belogs_to user event has_many boxes through event_box_mappings 

i'm trying achieve faster (and more memory efficient) csv generation through activeadmin using postgresql's copy functionality stream output of raw sql directly csv export. achieve this, however, need pass raw sql string, i'm having trouble creating bits of information generated populate columns of our events csv. in particular, i'd pick out counts of distinct values of box_property_id column of boxes of events.

now, far, have following sql runs maps values of event , user models:

select      events.id,      events.user_id,      events.event_type,      events.promo_code,      events.created_at,      events.transport_fee,      events.boxes_count,      users.email,      users.gender,      users.first_name,      users.last_name  events  left join users on users.id = events.user_id` 

i'm stuck @ part mentioned above - include counts of "each kind of box" represented box_property_id field in boxes of event in table returned above sql.

i come nosql background past experience , new field, , apologise if query ambiguous/incomplete in form.

as understood, need wanna distinct count of box_property_id other columns.

event.joins(:user, event_box_mappings: :box)      .select("events.id, events.user_id, events.event_type, events.promo_code,              events.created_at, events.transport_fee, events.boxes_count,               users.email, users.gender, users.first_name, users.last_name,              count(distinct boxes.box_property_id) total") 

total return count of distinct box_property_id.

hope helpful


Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -