繁体   English   中英

Ruby On Rails中的活动记录分组

[英]Active Record Grouping in Ruby On Rails

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")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM