2
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,

The location of store-id(3) should be combained with comma as (yyy,xxx),

then the location of store-id(4) should be combained with comma as (zzz,aaa)

#< store_id: 3,location:'yyy,xxx'>
#< store_id: 4,location:'zzz,aaa'> 
Dheena
  • 117
  • 9

1 Answers1

0

Using Enumerable.group_by you can do it this way:

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.

For example, in MySQL (see Can I concatenate multiple MySQL rows into one field?)

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

Community
  • 1
  • 1