How to setup a association through multiple models

ruby, ruby-on-rails

Solution

You can use a `has_many` `through` relationship as outlined here

class Book < ActiveRecord::Base
    has_many :chapters
    has_many :pages, through: :chapters
end

class Chapter < ActiveRecord::Base
    belongs_to :book
    has_many :pages
end

class Page < ActiveRecord::Base
    belongs_to :chapter
end

That enables you to do `book.pages.count`

Problem

I've the followig three models in `Rails`: ``` class Book < ActiveRecord::Base has_many :chapters has_many :pages end class Chapter < ActiveRecord::Base belongs_to :book has_many :pages end class Page < ActiveRecord::Base belongs_to :chapter end ``` How is it possible do to a query like: `Book.first.pages.count` to get the number of pages of the whole book. By now I dont even know if i set my model up the right way. Would be great if you could help me out here. Thanks in advance!

Original source