# Best find for the job

**URL:** <https://www.ruby-forum.com/t/best-find-for-the-job/158829>\
**Category:** Rails\
**Created:** [January 28, 2009, 4:04pm UTC](https://www.ruby-forum.com/t/best-find-for-the-job/158829 "2009-01-28T16:04:26Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Neal\_L](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/74df32/32.png) [@Neal\_L](https://www.ruby-forum.com/u/Neal_L)\
**Post date:** [January 28, 2009, 4:04pm UTC](https://www.ruby-forum.com/t/best-find-for-the-job/158829/1 "2009-01-28T16:04:26Z")

</div>

Hi all,

I’m trying to find the most effective way to generate an aggregation  
report. The models involved are:

Customer --(has\_many)–\> Charges  
Charges --(have\_one)–\>Account

What I’m trying to do is find the total charges during the year for  
each customer by account. In other words, a function like:

customer.charges\_for\_year()

in the customer model that will return a hash of each account charged  
and the customer’s total charges to that account.

From what I’ve read I don’t think I should be using named\_scope, since  
this involves associations…

Any ideas?

Thanks!

---

<div class="post-metadata">

**Author:** ![Neal\_L](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/74df32/32.png) [@Neal\_L](https://www.ruby-forum.com/u/Neal_L)\
**Post date:** [January 28, 2009, 4:29pm UTC](https://www.ruby-forum.com/t/best-find-for-the-job/158829/2 "2009-01-28T16:29:49Z")

</div>

In my opinion, the best way is the first way that works. If that  
method proves to be too inefficient, then optimize afterwards.

---

<div class="post-metadata">

**Author:** ![Neal\_L](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/74df32/32.png) [@Neal\_L](https://www.ruby-forum.com/u/Neal_L)\
**Post date:** [January 28, 2009, 10:33pm UTC](https://www.ruby-forum.com/t/best-find-for-the-job/158829/3 "2009-01-28T22:33:16Z")

</div>

Neal L wrote:

> What I’m trying to do is find the total charges during the year for  
> each customer by account. In other words, a function like:

I’m guessing that the most efficient way to accomplish this (that is  
without doing some data caching), would be to let the database handle  
it.

## If you had a database view configured something like this:

## customer\_charges (DB View)

## select t0.customer\_name, sum(t1.amount) as amount from customers t0 join charges t1 on t0.id=t1.customer\_id group by t0.id, t1.account\_id having year(t1.created\_at)=year(current\_date());

Then you could create a model that manages this report data:

CustomerCharge \<\< ActiveRecord::Base  
def readonly?  
true  
end  
end

Note: This is all written off of top of my head with absolutely not  
tested.

Another option might be to create a class in Ruby that mimics a database  
view by executing some raw SQL.
