[英]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'> ]>
How to group location in comma seperated form based on store_id in ruby to get the result as, 如何基于红宝石中的store_id以逗号分隔的形式对位置进行分组以获取结果,
The location of store-id(3) should be combained with comma as (yyy,xxx), store-id(3)的位置应与逗号(yyy,xxx)组合,
then the location of store-id(4) should be combained with comma as (zzz,aaa) 那么store-id(4)的位置应与逗号(zzz,aaa)组合
#< store_id: 3,location:'yyy,xxx'>
#< store_id: 4,location:'zzz,aaa'>
Using Enumerable.group_by you can do it this way: 使用Enumerable.group_by可以这样:
User.all.group_by(&:store_id).map{|store_id,records| {store_id: store_id, location: records.map(&:location).join(',')}}
If you want to do the grouping on database level, using the group method from ActiveRecord, it is required to have a function on the database that takes care of the concatenation, so the solution would depend on the database being used. 如果要使用ActiveRecord中的group方法在数据库级别进行分组,则需要在数据库上具有负责串联的功能,因此解决方案将取决于所使用的数据库。
For example, in MySQL (see Can I concatenate multiple MySQL rows into one field? ) 例如,在MySQL中(请参阅我可以将多个MySQL行连接到一个字段中吗? )
User.group("store_id").select("store_id, GROUP_CONCAT(location SEPARATOR ',') as location")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.