gpt4 book ai didi

ruby-on-rails - Group ActiveRecord::Relation By Field Into Hash With Dictionary

转载 作者:行者123 更新时间:2023-12-05 09:15:58 25 4
gpt4 key购买 nike

我正在运行一个返回大量记录的 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

最佳答案

您可以使用 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}]}

关于ruby-on-rails - Group ActiveRecord::Relation By Field Into Hash With Dictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51255717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com