query optimisation

This commit is contained in:
Meutel 2015-08-04 19:32:38 +02:00
parent 76771541e9
commit 1030170c47
4 changed files with 20 additions and 9 deletions

View File

@ -16,8 +16,9 @@ class AuthorsController < ApplicationController
end end
def index def index
@authors = Author.where(query_filter).order(:sort) @authors = Author.where(query_filter)
.paginate(page: params[:page], per_page: @preference.per_page) .order(:sort)
.paginate(pagination)
@title = "Authors" @title = "Authors"
respond_to do |format| respond_to do |format|
format.html format.html

View File

@ -10,8 +10,10 @@ class BooksController < ApplicationController
end end
def index def index
@books = Book.where(query_filter).order(sort_col) @books = Book .where(query_filter(Book.table_name))
.paginate(page: params[:page], per_page: @preference.per_page) .includes(:authors, :serie) .references(:authors, :serie)
.order(sort_col)
.paginate(pagination)
@title = "Books" @title = "Books"
respond_to do |format| respond_to do |format|
format.html format.html

View File

@ -9,8 +9,11 @@ class SeriesController < ApplicationController
end end
def index def index
@series = Serie.where(query_filter).order(:sort) @series = Serie.where(query_filter(Serie.table_name))
.paginate(page: params[:page], per_page: @preference.per_page) .includes(books: :authors)
.references(:books)
.order(:sort)
.paginate(pagination)
@title = "Series" @title = "Series"
respond_to do |format| respond_to do |format|
format.html format.html

View File

@ -17,18 +17,23 @@ module PreferencesHelper
session[:preference] = @preference.to_json session[:preference] = @preference.to_json
end end
def query_filter def query_filter(prefix = nil)
sort_col = prefix ? prefix + ".sort" : "sort"
conditions = Array.new conditions = Array.new
params = Array.new params = Array.new
if @preference.initial if @preference.initial
conditions.push "UPPER(sort) LIKE ?" conditions.push "UPPER(#{sort_col}) LIKE ?"
params.push "#{@preference.initial}%" params.push "#{@preference.initial}%"
end end
if @preference.term if @preference.term
conditions.push "sort LIKE ?" conditions.push "#{sort_col} LIKE ?"
params.push "%#{@preference.term}%" params.push "%#{@preference.term}%"
end end
[ conditions.join(" AND ") ] + params [ conditions.join(" AND ") ] + params
end end
def pagination
{ page: params[:page], per_page: @preference.per_page }
end
end end