ruby on rails - Active Record, count of grandchild association record -


let's i've got:

class town < activerecord::base   has_many :citizens end  class citizen < activerecord::base   belongs_to :town   has_many :cars end  class car < activerecord::base   belongs_to :citizen end 

using activerecord, simplest way can count of cars in town?

in models can define through association.

class town < activerecord::base   has_many :citizens   has_many :cars , :through => :citizens end 

and query this.

@town.cars.count 

or

town.find("town id").cars.count 

Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo