Remember_me
Remember_me

Reputation: 283

Group list of objects/AR relation by user_id

I have a list of objects which is actually AR Relation. My object has these fields :

{
  agreement_id: 1,
  app_user_id: 1,
  agency_name: 'Small business 1'
  ..etc..
},
{
  agreement_id: 2,
  app_user_id: 1,
  agency_name: 'Small business 2'
  ..etc..
}

I m representing my object as a Hash for easier understanding. I need to map my list of objects to format like this :

{
  1 => [1,2]
}

This represents a list of agreement_ids grouped by the user. I always know which user I m grouping on. Here is what I've tried so far :

where(app_user_id: user_id).where('...').select('app_user_id, agreement_id').group_by(&:app_user_id)

This gives me the structure what I want but not exactly the data that I want, here is an output of this :

{1=>
  [#<Agreement:0x6340fdbb agreement_id: 1, app_user_id: 1>,
   #<Agreement:0x91bd4dd agreement_id: 2, app_user_id: 1>]
 }

I've also thought I was going to be able to do this with map method, and here is what I tried :

where(app_user_id: user_id).where('....').select('app_user_id, agreement_id').map do |ag|
  { ag.app_user_id => ag.agreement_id } 
end.reduce(&:merge) 

But it only produces the mapping with the last agreement_id like this :

{1=>2}

I've tried some other things not worth mentioning. Can anyone suggest a way that would make this work?

Upvotes: 0

Views: 26

Answers (2)

ant
ant

Reputation: 22948

This might work :

where(app_user_id: user_id)
  .where('...')
  .select('app_user_id, agreement_id')
  .group_by(&:app_user_id).map{|k,v| Hash[k, v.map(&:agreement_id)]}

Upvotes: 1

Ursus
Ursus

Reputation: 30071

Try this one

where(app_user_id: user_id).
  where('...').
  select('app_user_id, agreement_id').
  map { |a| [a.app_user_id, a.agreement_id] }.
  group_by(&:first)

Upvotes: 1

Related Questions