I'm renewing a small library app and my search filter (pg_search) doesn't work with a model that is referenced with another (in this case, model Book as User references, for each user to have it's own set of books). But if i delete the references, the search works... In the case that if the books were available to every user but that's not the purpose. What am i missing? Thanks in advance for any help.
Book.rb
class Book < ApplicationRecord
belongs_to :user
include PgSearch::Model
pg_search_scope :search_by_full_name, against: [:title, :author],
using: { tsearch: { prefix: true } }
validates :title, presence: true
validates :author, presence: true
end
User.rb
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :books
end
books_controller.rb
class BooksController < ApplicationController
def index
if params[:term].present?
@books = Book.search_by_full_name(params[:term])
else
@books = Book.all
end
end
def show
@book = Book.find(params[:id])
end
def new
@user = User.find(params[:user_id])
@book = Book.new
end
def create
@user = User.find(params[:user_id])
@book = Book.new(book_params)
@book.user = @user
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])
end
def update
@book = Book.find(params[:id])
@book.update(book_params)
redirect_to user_book_path
end
def destroy
@book = Book.find(params[:id])
@book.destroy
redirect_to user_books_path
end
private
def book_params
params.require(:book).permit(:title, :author, :photo, :comments)
end
end
_search_book.html.erb
<%= form_tag user_books_path(current_user.id, @book), method: :get do %>
<%= text_field_tag 'term', params[:term], placeholder: "Enter title or author" %>
<%= submit_tag 'Search!' %>
<% end %>
It's solved... I was using current_user on the views instead of applying all the method on the controller and on the view leave it with only the model instance. Thanks everyone