Group activerecord relation

家住魔仙堡 提交于 2019-12-24 03:59:28

问题


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.



来源:https://stackoverflow.com/questions/21481047/group-activerecord-relation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!