Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup a association through multiple models

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!

like image 650
Sean M. Avatar asked Jan 10 '23 07:01

Sean M.


1 Answers

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

like image 65
Anthony Avatar answered Jan 19 '23 21:01

Anthony