Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using group_by in rails/ruby

Here is my array:

finalcount = Vote.where(:month => month, :year => year, :vote_id => vote.id).count

I'd like to use group_by (I think?) to group the votes by user_id (which each vote has), and then return the user_id with the highest votes.

Any ideas how I can do this?

like image 532
Elliot Avatar asked Mar 13 '11 20:03

Elliot


2 Answers

Have you tried the group method?

finalcount = Vote.where(:month => month, :year => year, :vote_id => vote.id).group(:user_id).count

will give you a Hash where the keys are the user_id and the values are the count. You can then call max on this result to get a two-element array containing the user_id and the count.

Here's an example from an app I have handy, where I use the result of the calculation to find the correct model instance and read properties from it:

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"
like image 121
Michelle Tilley Avatar answered Sep 21 '22 00:09

Michelle Tilley


I think what you really want is this:

Vote.select("votes.user_id, count(votes.id)").
  where(:month => month, :year => year, :id => vote.id).
  group("votes.user_id").
  order("count(votes.id) DESC").
  limit(1)

This will grab the user_id and count of votes they have, but only return the one with the most votes.

Why did your originall call have :vote_id => vote.id? Does your Vote model really have a column named vote_id and is it different than it's normal id?

like image 31
nzifnab Avatar answered Sep 22 '22 00:09

nzifnab