group_by in rails by 2 or more attributes

RubyRuby on-Rails-3Group By

Ruby Problem Overview


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?

Ruby Solutions


Solution 1 - Ruby

Why not do:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNick GinantoView Question on Stackoverflow
Solution 1 - RubysawaView Answer on Stackoverflow