Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 328
Matt Elhotiby Avatar asked Nov 30 '22 05:11

Matt Elhotiby


1 Answers

grouped_sales = recent_sales.group_by { |s| [s.contact_id, s.event_id] }
                .map { |k,v| [k.first, k.last, v.length] }
like image 162
mikdiet Avatar answered Dec 05 '22 12:12

mikdiet