# Grouping recs by user, then averaging

**URL:** <https://www.ruby-forum.com/t/grouping-recs-by-user-then-averaging/141257>\
**Category:** Rails\
**Created:** [June 24, 2008, 3:51am UTC](https://www.ruby-forum.com/t/grouping-recs-by-user-then-averaging/141257 "2008-06-24T03:51:44Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![bob](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/ea666f/32.png) [@bob](https://www.ruby-forum.com/u/bob)\
**Post date:** [June 24, 2008, 3:51am UTC](https://www.ruby-forum.com/t/grouping-recs-by-user-then-averaging/141257/1 "2008-06-24T03:51:44Z")

</div>

I’m wondering if there’s a way in RoR other than going to raw SQL to  
take a table of scores, group and sum them by each user, then average  
those values?

So far, I’ve got:  
@gpointsallcum = Gamepoint.average(:pointvalue)|| 0  
@gpointsalllastweek = Gamepoint.average(:pointvalue, :conditions  
=\> [“created\_at \>= ? and created\_at \<= ?”,  
datelastweek,datethisweek])|| 0  
@gpointsallthisweek = Gamepoint.average(:pointvalue, :conditions  
=\> [“created\_at \>= ?”, datethisweek]) || 0

But this is just averaging across all scores…

Any help appreciated!

---

<div class="post-metadata">

**Author:** ![bob](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/ea666f/32.png) [@bob](https://www.ruby-forum.com/u/bob)\
**Post date:** [June 24, 2008, 2:43pm UTC](https://www.ruby-forum.com/t/grouping-recs-by-user-then-averaging/141257/2 "2008-06-24T14:43:36Z")

</div>

On 24 Jun 2008, at 02:50, Bob W. wrote:

> @gpointsallthisweek = Gamepoint.average(:pointvalue, :conditions  
> =\> [“created\_at \>= ?”, datethisweek]) || 0

sum, average etc… take a :group option if that’s what you’re asking.

Fred

---

<div class="post-metadata">

**Author:** ![bob](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/ea666f/32.png) [@bob](https://www.ruby-forum.com/u/bob)\
**Post date:** [June 24, 2008, 4:26pm UTC](https://www.ruby-forum.com/t/grouping-recs-by-user-then-averaging/141257/3 "2008-06-24T16:26:57Z")

</div>

On Jun 24, 9:50 am, Bob W. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:  
I think you can use named\_scope for last\_week and this\_week, and  
has\_many relationships between user and the gamepoint, so that will  
give you user.gamepoints.last\_week and user.gamepoints.this\_week.

Then you can use collect to get the point values and do the sum and  
average.
