Group_by - Membership__Connection

I would like to use the group_by method, but instead of using a column in the database:

@posts.group_by(&:date)

I want to have something like:

@ posts.group_by (&: author)

If the message belongs to the author.

Am I just not sure about the syntax?

+3
source share
2 answers

You can write in your model:

def author_name
  self.author.name
end

and then

@posts.group_by(&:author_name)
+5
source

In this case, presumably you could just do

@posts.group_by(&:author_id)

More generally, you can pass a group_by block, so if you need to group by some arbitrary logic:

@posts.group_by { |post|
  ... some code returning a value to group this post by ...
} 

, , , , group_by , , , "" , , , , group_by.

+1

Source: https://habr.com/ru/post/1708794/


All Articles