# Using group in with find in an ActiveRecord appropriately

**URL:** <https://www.ruby-forum.com/t/using-group-in-with-find-in-an-activerecord-appropriately/130153>\
**Category:** Rails\
**Created:** [February 25, 2008, 9:36pm UTC](https://www.ruby-forum.com/t/using-group-in-with-find-in-an-activerecord-appropriately/130153 "2008-02-25T21:36:09Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![rob](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/838e76/32.png) [@rob](https://www.ruby-forum.com/u/rob)\
**Post date:** [February 25, 2008, 9:36pm UTC](https://www.ruby-forum.com/t/using-group-in-with-find-in-an-activerecord-appropriately/130153/1 "2008-02-25T21:36:09Z")

</div>

I’m playing around with the Practical Rails Projects code, and was  
attempting to make a change for graphing data differently using  
groupings.

Basically the code went from:  
total\_weight = @exercise.activities.collect {|e| e.repetitions

- e.resistance}  
workout\_dates = @exercise.activities.collect {|e|  
e.workout.date.to\_s}

To:  
total\_weight = @exercise.activities.find(  
:all,  
:select =\>  
“sum( repetitions \* resistance ) AS resistance”,  
:group =\>  
“workout\_id”,  
:order =\>  
“workout\_id”  
).collect{ |e| e.resistance }  
workout\_dates = @exercise.activities.find(  
:all,  
:group =\>  
“workout\_id”,  
:order =\>  
“workout\_id”  
).collect {|e| e.workout.date.to\_s}

Now, the total\_weight array works fine in the new implementation, but  
the generation of it is much less than optimal. I’m renaming the sum  
as an existing column so I can collect it, which is just a nasty hack.

How can this be done better? I understand I can use  
Enumerable#group\_by, but I want the db to do this one.
