I just finished going over Chris's two great railscasts dealing with search. However, I wanted to put my search bar on my navbar so that whenever someone searches the results I will be taken to my search.html.erb within my books folder (similar to how Gorails works). I ran into an issue though, everytime I did a search I was taken to my books page [http://localhost:3000/books?utf8=%E2%9C%93&q=travel] with no results being shown just my standard index showing all my books and was never taken to my search results page. I've listed all my relevant code below. If anyone can help me out would be super grateful. Thank you guys so much!
class Book < ApplicationRecord has_many :likes, :counter_cache => true has_many :users, through: :likes searchkick end
class BooksController < ApplicationController before_action :authenticate_user!, only: [:new, :create] before_action :set_book, only: [:show, :edit, :update, :destroy, :share] def index @books = Book.all end def search @booksearches = Book.search(params.fetch(:q, "*")) end private def set_book @book = Book.find(params[:id]) end def book_params params.require(:book).permit(:title, :author, :avatar) end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception def search @booksearches = Book.search(params.fetch(:q, "*")) end end
Researched, hacked through trial and error but was finally able to get it to work. If anyone else has a similar issue, I've outlined what worked for me below.
Add a post to your routes file so that a user can go to the search results page.
post 'books/search' => 'books#search', as: 'search_books'
2.Adjust your form_tag on your application.html.erb so that it can properly point to your search results page
<%= form_tag search_books_path do %>
<%= text_field_tag :q, nil, placeholder: "Search..." %>
<% end %>
In your search.html.erb make sure to list out your search results
<% @booksearches.each do |booksearch| %>
Join 24,647+ developers who get early access to new screencasts, articles, guides, updates, and more.