Ruby on rails rubyonrails中的活动记录分组

Ruby on rails rubyonrails中的活动记录分组,ruby-on-rails,ruby,Ruby On Rails,Ruby,如何基于ruby中的store_id以逗号分隔的形式对位置进行分组,以获得如下结果: store-id3的位置应与逗号组合为yyy,xxx 然后store-id4的位置应该用逗号组合为zzz,aaa record = #<ActiveRecord::AssociationRelation [#<User id: 2, store_id: 3,location: 'xxx'>, #<User id: 4, store_id: 3,location:'yyy'>,

如何基于ruby中的store_id以逗号分隔的形式对位置进行分组,以获得如下结果:

store-id3的位置应与逗号组合为yyy,xxx

然后store-id4的位置应该用逗号组合为zzz,aaa

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'> ]>

通过使用Enumerable.group_,您可以通过以下方式执行此操作:

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

如果要使用ActiveRecord中的group方法在数据库级别进行分组,则需要在数据库上具有一个处理连接的函数,因此解决方案将取决于所使用的数据库

例如,在MySQL中,请参见


User.groupstore\u id.selectstore\u id,GROUP\u CONCATlocation SEPARATOR',as location

您希望如何分组?按门店标识、按地点还是同时按两者?你的问题不清楚。你真的是在要求分类而不是分组吗?看起来,从你提供的小信息来看,你需要排序。我需要按存储区分组。我已经更新了问题,我不需要排序
#< store_id: 3,location:'yyy,xxx'>
#< store_id: 4,location:'zzz,aaa'>