loading...

Two ways of grouping a dataset

n350071 profile image n350071🇯🇵 ・1 min read

ActiveRecord::QueryMethods#group

omit..

Array#group_by

It's useful when you want a hash such like

  • key: the group id
  • value: objects

You can get it by like this

Book.includes(:author).group_by{|book| book.author.name }

#=>
{
'Jhon' => [A, D, E],
'Alex' => [B, C]
}
# A,B,..E are Book objects.

Discussion

pic
Editor guide
 

Presumably you would also want an array and not an AR relation?