Accessing has_many objects

I have a the following models

CLIENT - has_many -> CAMPAIGNS - has_many -> CODES -> has_many ->HITS

So obviously a client has many codes, but each is linked to a campaign. Now I have managed to get all the codes by using

has_many :codes, :through=>:campaigns

so the model looks like this

class Client < User   has_many :campaigns   has_many :codes, :through=>:campaigns

Now is it possible to make the client have many hits, which would encompass all hits on all codes over all campaigns. Or Do I have to loop through every campaign and every code and every hit to find all the hits for a client.

Try :

has_many :codes, :through=>:campaigns, :include => :hits

then

client.codes.map(&:hits).inject(&:+)

Actually, that'd depend on what's exactly inside yout Hit model.

My hit model has a month, a year and a hit count, and obv a code_id.

what does client.codes.map(&:hits).inject(&:+) do? i.e the map(&:hits).inject(&:+)

Ah. Try :

In client.rb : has_many :codes, :through=>:campaigns, :include => :hits

def hits   self.codes.map(&:hits).flatten.map(&:hit_count).inject(&:+) end

Then for example : client = Client.find(:first).hits

Explaination of "self.codes.map(&:hits).flatten.map(&:hit_count).inject(&:+)" do :

- self.codes will get you all associatied codes. - .map(&:hits) will return array of associatiated hits with codes. It'll be an array of array. So we use .flatten - map(&:hit_count) will return array of hit_count from all Hit objects in the array - inject(&:+) is just a fancy way to do sum.

e.g. [1,2,3].inject(&:+) => 6

That sounds great. Thanks Alot.