group_by in rails由2个或更多属性组成 [英] group_by in rails by 2 or more attributes

查看:147
本文介绍了group_by in rails由2个或更多属性组成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 @bunch 作为数组返回的模型

每个模型都有属性 - commentable_id commentable_type (多态关联)



这些模型由可评论的,但如果我做的话

  @ bunch.group_by(&:commentable)

它还从数据库中提取可评论的内容,这是不需要的。



我可以做 @ bunch.group_by(&:commentable_id)但这会引起一些混淆,因为可以有几种类型的可评论模型



有没有办法< group_by commentable_id AND commentable_type code>?

解决方案

为什么不这样做:

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


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?

解决方案

Why not do:

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

这篇关于group_by in rails由2个或更多属性组成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆