John
John

Reputation: 634

Group activerecord relation

After a select on a table I get a result:

[#<Result url: "http://www.url.com/1", key_id: 1>, 
#<Result url: "http://www.url.com/1", key_id: 2> [...]

How can I group the url and keep the key_id, something like:

["http://www.url.com/1", [1, 2]]=>2

Thank you

Upvotes: 2

Views: 2374

Answers (1)

marvelousNinja
marvelousNinja

Reputation: 1510

Here's the code:

grouped_results = Result.all.group_by(&:url).map do |url, results|
  { [url, results.map(&:key_id)] => results.count }
end

You need to replace Result.all by your actual scope or something.

Upvotes: 3

Related Questions