Rails Search return all itens instead of searched one's

76 Views Asked by At

I have a rails app that consists on a personal library and i had a search feature that started to always returning all items on database and not only the searched item. The URL after each search comes like this, for example:

http://localhost:3000/users/user_id/books?search=Alquimia

But returns all and not only that specific one... Thanks in advance for all help you can give me.

The code is as follow: (i'll post two ways i tryed, the first on using PGsearch)

1'ST TRY

books_controller.rb

def index
    if params[:term].present? 
      @books = Book.search_by_full_name(params[:term])
      @books = policy_scope(Book)
    else
      @books = Book.all
      @books = policy_scope(Book)
    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 %>

book.rb

class Book < ApplicationRecord
 
  belongs_to :user
  has_many :loans
  

  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
      }
    }

end

2'ND TRY

books_controller.rb

  def index  
    if params[:search]
      @books = Book.where('name LIKE ?', "%#{params[:search]}%")
      @books = policy_scope(Book)
    else
      @books = Book.all
      @books = policy_scope(Book)
    end
  end

_book_search_bar.html.erb

<%= form_tag user_books_path(:user_id), method: :get do %>
2    <%= label_tag  "Search for a book:" %>
3    <%= text_field_tag :search, params[:search] %>
4    <%= submit_tag 'Search', name: nil %>
5  <% end %>
0

There are 0 best solutions below