Skip to content

Commit

Permalink
Fix n+1 select query for book's index page
Browse files Browse the repository at this point in the history
  • Loading branch information
bry4n committed Jun 28, 2012
1 parent 3b20e01 commit 914f4d8
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 5 deletions.
4 changes: 3 additions & 1 deletion app/controllers/doc_controller.rb
@@ -1,7 +1,7 @@
class DocController < ApplicationController
layout "layout"

before_filter :book_resource, :only => [:index, :book, :book_section, :progit]
before_filter :book_resource, :only => [:index, :book_section, :progit]

def index
@videos = VIDEOS
Expand Down Expand Up @@ -66,6 +66,8 @@ def man
end

def book
@book = Book.includes(:sections).where(:code => (params[:lang] || "en")).first
raise PageNotFound unless @book
end

def book_section
Expand Down
5 changes: 3 additions & 2 deletions app/models/chapter.rb
Expand Up @@ -6,16 +6,17 @@ class Chapter < ActiveRecord::Base
default_scope :order => 'number'
belongs_to :book
has_many :sections
has_many :chapters, :through => :book

def prev
num = self.number - 1
return self.book.chapters.where(:number => num).first if num > 0
return self.chapters.where(:number => num).first if num > 0
false
end

def next
num = self.number + 1
return self.book.chapters.where(:number => num).first if num > 0
return self.chapters.where(:number => num).first if num > 0
false
end

Expand Down
5 changes: 3 additions & 2 deletions app/models/section.rb
Expand Up @@ -13,6 +13,7 @@ class Section < ActiveRecord::Base
has_one :book, :through => :chapter
before_save :set_slug
after_save :index
has_many :sections, :through => :chapter

def get_related(limit = 10)
ri = RelatedItem.where(:related_type => 'book', :related_id => slug).order('score DESC').limit(limit)
Expand All @@ -30,7 +31,7 @@ def set_slug
def prev_slug
lang = self.book.code
prev_number = self.number - 1
if section = self.chapter.sections.where(:number => prev_number).first
if section = self.sections.where(:number => prev_number).first
return "/book/#{lang}/#{section.slug}"
else
# find previous chapter
Expand All @@ -46,7 +47,7 @@ def prev_slug
def next_slug
lang = self.book.code
next_number = self.number + 1
if section = self.chapter.sections.where(:number => next_number).first
if section = self.sections.where(:number => next_number).first
return "/book/#{lang}/#{section.slug}"
else
if ch = self.chapter.next
Expand Down

0 comments on commit 914f4d8

Please sign in to comment.