简体   繁体   中英

How to use elasticsearch/searchkick to run a search bar on my navbar and show results in a specific page?

I just finished going over a few tutorials dealing with search. 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 SO works). I ran into an issue though, every time 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!

Book.rb

class Book < ApplicationRecord
has_many :likes, :counter_cache => true
has_many :users, through: :likes

searchkick
end

books_controller.rb

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

application_controller.rb

class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
def search
@booksearches = Book.search(params.fetch(:q, "*"))
end
end

application.html.erb

<body style="background-color: #f5f8fa; padding-top: 70px;" class="<%= @body_class %>">
<nav class="navbar navbar-default navbar-fixed-top">
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li>
            <%= form_tag books_path, method: :get do %>
                <%= text_field_tag :q, nil, placeholder: "Search..." %>
            <% end %>
        </li>         
      </ul>
</div>
</nav>
</body>

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.

Three Steps

  1. 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 %>

  1. In your search.html.erb make sure to list out your search results

<% @booksearches.each do |booksearch| %><div><h3><%= link_to booksearch.title, booksearch %></h3></div> <% end %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM