0

I'm trying to group a large table by a foreign key in order to make some changes to those records.

What I would like to do is group(:foreign_key_id) and return the ids in this group. So I would get: {foreign_key_id => [array of ID's with this key], {foreign_key_id => [array of ID's with this key] }

Maybe I should be mapping the (&:id) value, but this function sits behind a where so it's not all records of this foreign key that are returned.

My working code would be something like this:

SubscriptionTag.where(subscription_id: @paper.subscriptions.map(&:id).group(:tag_id)

This returns all unique tags used by my subset of subscriptions. Now I would like to also return the SubscriptionTag ids along with each tag_id

I hope this makes sense.

David Sigley
  • 1,126
  • 2
  • 13
  • 28

1 Answers1

1

Based on this answer, you can use pluck with array_agg and then #to_h:

Subscription.group(:tag_id).pluck(:tag_id, 'array_agg(id)').to_h
Pavel Mikhailyuk
  • 2,757
  • 9
  • 17