ruby - group_by in rails by 2个或更多属性

标签 ruby ruby-on-rails-3 group-by

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

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

我想按可评论的方式对模型进行分组,但如果这样做的话

@bunch.group_by(&:commentable)

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

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

有没有办法group_by commentable_id AND commentable_type

最佳答案

为什么不这样做:

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

关于ruby - group_by in rails by 2个或更多属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14660644/

相关文章:

Mysql(和 Postgresql)在 where = 1 和 in(1) 上的性能

mysql - 总和的计数

ruby-on-rails - 升级到 Rails 3.2.2 : How to solve the 'undefined method for Syck::DomainType' error related to the Delayed Job gem?

ruby - Rails 3 - 通过 Controller 中的正则表达式检查字符串/文本是否包含某个单词/字符

Ruby 元编程 : adding @variables to existing 'initialize' method (using class_eval)

ruby-on-rails - Rails 入门教程中的 TypeError

ruby-on-rails - 为什么这会在 Ruby on Rails 3 中返回 Nil?

r - group_by 跨多列的唯一计数

mysql - 在给定时间范围内按小时分组

ruby-on-rails - 从多个 ActiveRecord 查询创建 Ruby 哈希的有效方法