DEV Community

n350071πŸ‡―πŸ‡΅
n350071πŸ‡―πŸ‡΅

Posted on

Two ways of grouping a dataset

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.

Top comments (1)

Collapse
 
bizzibody profile image
Ian bradbury

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