DEV Community

n350071🇯🇵
n350071🇯🇵

Posted on

2 1

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?

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay