From 1030170c471c78cda2b76c214ccd7ba6ceba5e09 Mon Sep 17 00:00:00 2001 From: Meutel Date: Tue, 4 Aug 2015 19:32:38 +0200 Subject: [PATCH] query optimisation --- app/controllers/authors_controller.rb | 5 +++-- app/controllers/books_controller.rb | 6 ++++-- app/controllers/series_controller.rb | 7 +++++-- app/helpers/preferences_helper.rb | 11 ++++++++--- 4 files changed, 20 insertions(+), 9 deletions(-) diff --git a/app/controllers/authors_controller.rb b/app/controllers/authors_controller.rb index e2c6ce2..8b27163 100644 --- a/app/controllers/authors_controller.rb +++ b/app/controllers/authors_controller.rb @@ -16,8 +16,9 @@ class AuthorsController < ApplicationController end def index - @authors = Author.where(query_filter).order(:sort) - .paginate(page: params[:page], per_page: @preference.per_page) + @authors = Author.where(query_filter) + .order(:sort) + .paginate(pagination) @title = "Authors" respond_to do |format| format.html diff --git a/app/controllers/books_controller.rb b/app/controllers/books_controller.rb index 67b076a..2274f1b 100644 --- a/app/controllers/books_controller.rb +++ b/app/controllers/books_controller.rb @@ -10,8 +10,10 @@ class BooksController < ApplicationController end def index - @books = Book.where(query_filter).order(sort_col) - .paginate(page: params[:page], per_page: @preference.per_page) + @books = Book .where(query_filter(Book.table_name)) + .includes(:authors, :serie) .references(:authors, :serie) + .order(sort_col) + .paginate(pagination) @title = "Books" respond_to do |format| format.html diff --git a/app/controllers/series_controller.rb b/app/controllers/series_controller.rb index b180f27..b129472 100644 --- a/app/controllers/series_controller.rb +++ b/app/controllers/series_controller.rb @@ -9,8 +9,11 @@ class SeriesController < ApplicationController end def index - @series = Serie.where(query_filter).order(:sort) - .paginate(page: params[:page], per_page: @preference.per_page) + @series = Serie.where(query_filter(Serie.table_name)) + .includes(books: :authors) + .references(:books) + .order(:sort) + .paginate(pagination) @title = "Series" respond_to do |format| format.html diff --git a/app/helpers/preferences_helper.rb b/app/helpers/preferences_helper.rb index 6a00b72..d27f8bf 100644 --- a/app/helpers/preferences_helper.rb +++ b/app/helpers/preferences_helper.rb @@ -17,18 +17,23 @@ module PreferencesHelper session[:preference] = @preference.to_json end - def query_filter + def query_filter(prefix = nil) + sort_col = prefix ? prefix + ".sort" : "sort" conditions = Array.new params = Array.new if @preference.initial - conditions.push "UPPER(sort) LIKE ?" + conditions.push "UPPER(#{sort_col}) LIKE ?" params.push "#{@preference.initial}%" end if @preference.term - conditions.push "sort LIKE ?" + conditions.push "#{sort_col} LIKE ?" params.push "%#{@preference.term}%" end [ conditions.join(" AND ") ] + params end + def pagination + { page: params[:page], per_page: @preference.per_page } + end + end