group_by in rails by 2 or more attributes

旧街凉风 提交于 2019-12-20 10:29:43

问题


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?


回答1:


Why not do:

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


来源:https://stackoverflow.com/questions/14660644/group-by-in-rails-by-2-or-more-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!