How to group by two conditions in rails 3 and loop through them

14,501

Solution 1

grouped_sales = recent_sales.group_by { |s| [s.contact_id, s.event_id] }
                .map { |k,v| [k.first, k.last, v.length] }

Solution 2

Simply, try

group(['contact_id','event_id'])

It worked for me. So, I posted as answer to help others as well.

Solution 3

Ask the database to do the grouping

grouped_sales = recent_sales.group([:contact_id, :event_id]).count

the result is a hash each key is an array of the contact and event id, and the value is the count.

So if you want arrays of three

grouped_sales = recent_sales.group([:contact_id, :event_id]).count.map{ |k,v| k << v }
Share:
14,501
Matt Elhotiby
Author by

Matt Elhotiby

Interests: Javascript, React and Rails

Updated on June 13, 2022

Comments

  • Matt Elhotiby
    Matt Elhotiby almost 2 years

    Ok so I have a sale model that

    recent_sales = Sale.recent
     => [#<Sale id: 7788, contact_id: 9988, purchasing_contact_id: 876, event_id: 988, #<BigDecimal:7fdb4ac06fe8,'0.0',9(18)>, fulfilled_at: nil, skip_print: nil, convention_id: 6, refund_fee: #<BigDecimal:7fdb4ac06de0,'0.0',9(18)>, processing: false>, #<Sale id: 886166, , contact_id: 7775,
    
    recent_sales.count
    => 32
    

    I know i can do this

    grouped_sales = recent_sales.group_by(&:contact_id).map {|k,v| [k, v.length]}
    => [[9988, 10], [7775, 22]]
    

    But what i really need is not just grouping on contact_id but also event_id so the final results looks like this

    => [[9988, 988, 5], [9988, 977, 5], [7775, 988, 2], [7775, 977, 20]]
    

    so i have the event_id and the grouping is splitting them up correctly...any ideas on how to do this

    I tried

     recent_sales.group('contact_id, event_id').map {|k,v| [k, k.event, v.length]}
    

    but no go

  • W.M.
    W.M. over 6 years
    This works. Any idea how to get an associated model's value, e.g. name of the contact or date of an event (in the query result itself)?