I have a library management app with pg_search implemented; everything was working fine and all of the suddent it started to display all items on index but i didn't change anything regarding the feature. I'll leave all pertaining code, please tell me if it's needed something more. Thanks in advance.
book.rb
class Book < ApplicationRecord
belongs_to :user
has_many :loans
belongs_to :category
has_one_attached :photo
validates :title, presence: true
validates :author, presence: true
include PgSearch::Model
pg_search_scope :search_by_full_name, against: [:title, :author],
using: {
tsearch: {
prefix: true
}
}
def self.to_csv(options = {})
CSV.generate(options) do |csv|
csv << column_names
all.each do |book|
csv << book.attributes.values_at(*column_names)
end
end
end
#self.per_page = 12
end
book_controller.rb
class BooksController < ApplicationController
before_action :authenticate_user!
def index
if params[:term].present?
@books = Book.search_by_full_name(params[:term])
@books = policy_scope(Book)
else
@books = Book.paginate(page: params[:page])
@books = policy_scope(Book)
end
end
def show
@book = Book.find(params[:id])
authorize @book
end
def new
@user = User.find(params[:user_id])
@book = Book.new
@categories = Category.all.map{|c| [ c.name, c.id ] }
authorize @book
end
def create
@user = User.find(params[:user_id])
@book = Book.new(book_params)
# @book.category_id = params[:category_id]
@book.user = @user
authorize @book
if @book.save
redirect_to user_books_path
flash[:notice] = 'Success. Your book was added to the Library'
else
render "new"
flash[:notice] = 'Book not created. Please try again'
end
end
def edit
@user = User.find(params[:user_id])
@book = Book.find(params[:id])
@categories = Category.all.map{|c| [ c.name, c.id ] }
authorize @book
end
def update
@book = Book.find(params[:id])
@book.category_id = params[:category_id]
@book.update(book_params)
authorize @book
redirect_to user_book_path
end
def destroy
@book = Book.find(params[:id])
@book.destroy
authorize @book
redirect_to user_books_path
end
private
def book_params
params.require(:book).permit(:title, :author, :photo, :comments, :category_id)
end
end
_book_search_bar.html.erb
<%= form_tag user_books_path(:user_id), method: :get, class: "search-bar" do %>
<%= text_field_tag 'term', params[:term], placeholder: "Enter book or author" %>
<br>
<br>
<%= submit_tag "SEARCH BOOK", class: "btn-main" %>
<% end %>
You're just reassigning
@books = policy_scope(Book)which will remove both the search scope and pagination.Instead of the class pass an actual scope to pundit or flip it upside down:
Not likely. More likely is that the regressions were caused when implementing Pundit and there where no tests that detected it. Things don't happen magically.