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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With