How to set up communication through several models

I have the following 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 can I make a request like: Book.first.pages.countto get the number of pages of the entire book. At the moment, I don’t even know if I configured the model correctly. It would be great if you could help me here.

Thanks in advance!

+4
source share
2 answers

You can use relationships has_many throughas described 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

It allows you to do book.pages.count

+9
source

. , , - a Book Chapters Pages, a Chapter Pages. Pages Book a Chapter?

0

Source: https://habr.com/ru/post/1547017/


All Articles