这是我的数组:
finalcount = Vote.where(:month => month, :year => year, :vote_id => vote.id).count
我想使用 group_by
(我想?)按 user_id
(每个投票都有)对投票进行分组,然后返回 user_id
获得最高票数。
有什么想法可以做到这一点吗?
最佳答案
你试过group
方法吗?
finalcount = Vote.where(:month => month, :year => year, :vote_id => vote.id).group(:user_id).count
会给你一个Hash
,其中键是user_id
,值是count
。然后,您可以对该结果调用 max
以获得包含 user_id
和 count
的双元素数组。
这是我手边的一个应用程序示例,我在其中使用计算结果找到正确的模型实例并从中读取属性:
ruby-1.9.2-p136 :001 > ExternalPost.group(:service_id).count
=> {18=>1, 19=>1, 21=>4}
ruby-1.9.2-p136 :002 > ExternalPost.group(:service_id).count.max
=> [21, 4]
ruby-1.9.2-p136 :003 > Service.find(ExternalPost.group(:service_id).count.max.first).user.first
=> "Brandon"
关于ruby-on-rails - 在 rails/ruby 中使用 group_by,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5292309/