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?


Solution 1:

Why not do:

@bunch.group_by{|e| [e.commentable_id, e.commentable_type]}