开发者

How to model a book in MVC

How can I model a book in a MVC. I'm using Ruby on Rails.

A book has chapters, and chapters has pages.

Should I use a book as a model, or should there be s开发者_运维知识库eperate model each for book, chapter and then pages.


The most natural way of doing this is:

book.rb

class Book < ActiveRecord::Base
  has_many :chapters
end

chapter.rb

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

page.rb

class Page < ActiveRecord::Base
  belongs_to :chapter
end

Then in whatever view you are when you call your book (haml):

- for chapter in @book.chapters
  = chapter.title
  - for page in chapter.pages
    = page.content

and you can paginate however you see fit.

EDIT To @apneadiving point, added includes for N+1 queries. So from your books_controller.rb, to reduce the number of queries, you can call:

def show
  @book = Book.includes(:chapters => [:pages]).find(params[:id])
end

This will load the Book with all of its associated chapters and pages without having to do additional queries.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜