简体   繁体   English

将ActiveRecord关系转换为特定键控哈希

[英]Convert an ActiveRecord relation to a specifically keyed Hash

I have an ActiveRecord result set from the following query: 我有一个来自以下查询的ActiveRecord结果集:

people = People.where(job_type: ["Job Type 1", "Job Type 2"])

This returns an AcitveRecord Relation. 这将返回AcitveRecord关系。

I want to take people and convert it to a Hash where each key is the job_type and the value is an array of records that match that job_type . 我想带people并将其转换为Hash ,其中每个键都是job_type ,值是与job_type匹配的记录数组。

The closest thing I found is people.as_json but that gives an array of hashes, not the format I'd like to work with. 我发现最接近的是people.as_json但它提供了一系列哈希,而不是我想要使用的格式。

What's an elegant Ruby way of converting the people data structure? 什么是优雅的Ruby转换人员数据结构的方式? Ideally it would look like: 理想情况下它看起来像:

my_hash = {"Job Type 1" => [record1, record2..], "Job Type 2" => [..]}

It looks like you want to group_by job_type . 看起来你想要group_by job_type So, give this a go: 所以,试一试:

people = People.where(job_type: ["Job Type 1", "Job Type 2"]).group_by(&:job_type)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM