49

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?

4

1 回答 1

101

Why not do:

@bunch.group_by{|e| [e.commentable_id, e.commentable_type]}
于 2013-02-02T09:54:28.100 回答