gpt4 book ai didi

ruby-on-rails - Ruby On Rails 中的事件记录分组

转载 作者:太空宇宙 更新时间:2023-11-03 16:47:51 26 4
gpt4 key购买 nike

record = #<ActiveRecord::AssociationRelation 
[#<User id: 2, store_id: 3,location: 'xxx'>,
#<User id: 4, store_id: 3,location:'yyy'>,
#<User id: 5, store_id: 4,location:'zzz'>,
#<User id: 6, store_id: 4,location:'aaa'> ]>

如何根据 ruby​​ 中的 store_id 以逗号分隔形式对位置进行分组以获得结果,

store-id(3)的位置用逗号组​​合为(yyy,xxx),

然后 store-id(4) 的位置应该用逗号组合为 (zzz,aaa)

#< store_id: 3,location:'yyy,xxx'>
#< store_id: 4,location:'zzz,aaa'>

最佳答案

使用 Enumerable.group_by 你可以这样做:

User.all.group_by(&:store_id).map{|store_id,records| {store_id: store_id, location: records.map(&:location).join(',')}}

如果您想在数据库级别进行分组,使用 ActiveRecord 中的组方法,则需要在数据库上有一个函数来处理串联,因此解决方案将取决于所使用的数据库。

例如,在 MySQL 中(参见 Can I concatenate multiple MySQL rows into one field?)

User.group("store_id").select("store_id, GROUP_CONCAT(location SEPARATOR ',') as location")

关于ruby-on-rails - Ruby On Rails 中的事件记录分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29477067/

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