簡體   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