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'> ]>
如何基于红宝石中的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中的group方法在数据库级别进行分组,则需要在数据库上具有负责串联的功能,因此解决方案将取决于所使用的数据库。
例如,在MySQL中(请参阅我可以将多个MySQL行连接到一个字段中吗?)
User.group("store_id").select("store_id, GROUP_CONCAT(location SEPARATOR ',') as location")
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句