Ruby 3.1.2中合并哈希数组:按customer_id聚合product_id
解决方案
你遇到的问题核心是pluck是ActiveRecord集合专属方法,而group_by返回的分组元素是普通哈希对象,并非ActiveRecord实例,所以无法调用pluck。把pluck替换成map提取哈希中的:product_id即可实现需求:
data.group_by { |item| item[:customer_id] }.transform_values { |group| group.map { |h| h[:product_id] } }
也可以用更简洁的符号式写法:
data.group_by(&:[]).transform_values { |group| group.map { |h| h[:product_id] } }
进阶优化(针对ActiveRecord场景)
如果你的data是未触发查询的ActiveRecord Relation,建议直接在数据库层面完成分组聚合,比在Ruby内存中处理更高效:
- 适用于PostgreSQL:
data.select(:customer_id, :product_id) .group(:customer_id) .pluck(:customer_id, 'ARRAY_AGG(product_id)') .to_h
- 适用于MySQL(需要将拼接的字符串转为数组):
data.select(:customer_id, "GROUP_CONCAT(product_id SEPARATOR ',') AS product_ids") .group(:customer_id) .map { |row| [row.customer_id, row.product_ids.split(',')] } .to_h
内容的提问来源于stack exchange,提问作者Charles Dayman
相关产品推荐
相关产品推荐

