Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

group_by in rails by 2 or more attributes

I have a @bunch of models returned as an array

each model has the attributes - commentable_id and commentable_type (polymorphic association)

I want to group the models by commentable, but if I do

@bunch.group_by(&:commentable) 

it also fetches the commentable from the database, which is not needed.

I can do @bunch.group_by(&:commentable_id) but this will cause some confusions since there can be several types of commentable models

Is there a way to group_by commentable_id AND commentable_type?

like image 222
Nick Ginanto Avatar asked Feb 02 '13 09:02

Nick Ginanto


People also ask

What does Group_by do in Ruby?

The group_by() of enumerable is an inbuilt method in Ruby returns an hash where the groups are collectively kept as the result of the block after grouping them. In case no block is given, then an enumerator is returned. Parameters: The function takes an optional block according to which grouping is done.

What is group by in Rails?

Group by in ruby rails programming is one of the data types. The collection of enumerable sets is preliminary to group the results into a block. For instance, we can group the records by date. The group_by function in Ruby allows us to group objects by an arbitrary attribute.


1 Answers

Why not do:

@bunch.group_by{|e| [e.commentable_id, e.commentable_type]} 
like image 130
sawa Avatar answered Oct 31 '22 16:10

sawa