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)
Where post belongs_to author.
I'm just not sure of the syntax?
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)
Where post belongs_to author.
I'm just not sure of the syntax?
You can write in your model:
def author_name
self.author.name
end
and then
@posts.group_by(&:author_name)
In this instance presumably you could actually just do
@posts.group_by(&:author_id)
More generally, you can pass a block to group_by, so if you need to group on some arbitrary logic:
@posts.group_by { |post|
... some code returning a value to group this post by ...
}
As a hopefully related aside, last time I looked, the implementation of group_by preserves the relative order of the data fed to it, which can be useful to remember as it allows you to sort the data in the 'flat' list of posts, and then when you group them the order is maintained within the groupings, rather than dealing with sorting withing the nested data output by group_by.