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
?
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.
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.
Why not do:
@bunch.group_by{|e| [e.commentable_id, e.commentable_type]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With