Reputation: 346
I have a model Event
, it has an attribute ticket_id
. I'm grouping my events
by this attribute like this:
Event.group(:ticket_id).having('count(events.ticket_id) > 1')
and it is a perfectly working query, yet I don't understand how to work with the result of such a query directly.
I understand that I, for instance, may call method count
on it and get a hash with ticket_ids and number of corresponding events. But I need to get a structure with ticket_ids as keys and arrays of events as values like this one:
{ 1 => [#<Event:1>, #<Event:2>], 2 => [#<Event:3>, #<Event:4>], ... }
I can achieve such a result using plain ruby group_by
, but considering the fact that I have several millions of events it seems like not the best solution. Is it possible to achieve the result somehow using ActiveRecord or probably plain SQL?
P.S. I use PostgreSQL
Upvotes: 0
Views: 202
Reputation: 106802
ActiveRecord#group
creates a SQL GROUP BY
clause and that will always return a single list of items and not a nested data structure. Therefore the answer is: No you cannot create such a nested structure just with ActiveRecord
You would need to run something like groub_by(:events_count)
on the list returned from ActiveRecord
to translate the list into a nested structure.
Upvotes: 1