通过字段将ActiveRecord :: Relation按字段分组为带有字典的哈希

时间:2018-07-10 00:32:26

标签: ruby-on-rails activerecord

我正在运行一个ActiveRecord查询,该查询返回了一堆记录。

让我们以此为例

ad_account    campaign_id    impressions
1             1              500
1             2              8,800    
1             3              6,000
2             7              900
2             9              9,324

如何将这些结果转换为具有按ad_account分组的数组的哈希?

所以我想要这个

{"1"=>[{ad_account: 1, campaign_id: 1, impressions: 500}, {ad_account: 1, campaign_id: 2, impressions: 8,800}, {ad_account: 1, campaign_id: 3, impressions: 6,000}], 

"2"=>[{ad_account: 2, campaign_id: 7, impressions: 900}, {ad_account: 2, campaign_id: 9, impressions: 9324}]}

所以基本上每个ad_account是键,而值是所有字段的数组。

我该怎么做?

我已经尝试过了,但是因为它会覆盖

,所以它不起作用
allCampaigns.each do |campaign| 

    hash[campaign.ad_account] = campaign 

end

1 个答案:

答案 0 :(得分:1)

您可以使用group_by。例如:

Ad.all.group_by(&:ad_account)
# => { 1 => [#<Ad id: 1, ad_account: 1, campaign_id: 1, impressions: 500>,
#            #<Ad id: 2, ad_account: 1, campaign_id: 2, impressions: 8800>,
#            #<Ad id: 3, ad_account: 1, campaign_id: 3, impressions: 6000>],
#      2 => [#<Ad id: 4, ad_account: 2, campaign_id: 7, impressions: 900>,
#            #<Ad id: 5, ad_account: 2, campaign_id: 9, impressions: 9824>]}

这对查询结果起作用,对可枚举对象ActiveRecord::Relation起作用,它不会在您的sql查询中添加GROUP BY子句。

然后,如果您想要该哈希,则可以添加serializable_hash

Ad.all.group_by(&:ad_account).transform_values do |ads|
  ads.map do |ad|
    ad.serializable_hash(only: ['ad_account', 'campaign_id', 'impressions'])
  end
end
# { 1 => [{"ad_account"=>1, "campaign_id"=>1, "impressions"=>500},
#         {"ad_account"=>1, "campaign_id"=>2, "impressions"=>8800},
#         {"ad_account"=>1, "campaign_id"=>3, "impressions"=>6000}],
#   2 => [{"ad_account"=>2, "campaign_id"=>7, "impressions"=>900},
#         {"ad_account"=>2, "campaign_id"=>9, "impressions"=>9824}]}