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.
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.