Group activerecord relation

2019-07-16 12:30发布

问题:

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

回答1:

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.