views:

14

answers:

1

Let's say I have the following association:

Club has_many users
User has_many guns
Gun has_many bullets

Club: Moe, Larry, Curly

Moe: 2 guns
gun 1 has 100 bullets
gun 2 has 20 bullets

Larry: 1 gun
gun 1 has 40 bullets

Curly: 2 guns
gun 1 has 20 bullets
gun 2 has 10 bullets

Now, I want to find out how many bullets in the CLUB.

It's easy to use: Moe.bullets.sum(:amount) = 120 bullets.

But how can I get all of the bullets without iterating through each user?

Hope that makes sense.

BTW, I am using ActiveRecord and Rails 3.

Thanks!

+2  A: 

Hi cbmeeks,

I assume the gun 1 and gun 2 are the names and not a unique identifier. In that case,

Club has_many users User has_many guns Gun has_many bullets

Club: Moe, Larry, Curly

Gun : 1(Moe),2(Moe),3(Larry),4(Curly),5(Curly)

Moe: 2 guns (gun) 1 has 100 bullets (gun) 2 has 20 bullets

Larry: 1 gun (gun) 3 has 40 bullets

Curly: 2 guns (gun) 4 has 20 bullets (gun) 5 has 10 bullets

In which case, i would add the club id also to the gun table. with which we can directly get count of bullets a club has...

Or an alternative solution is to use counter_cache...

Hope it helps

rgds,

Kannan R

KannanR