I was able to get a basic search field working perfectly on my navbar using elasticsearch/searchkick. At the moment, the only way a query can be executed is if a user types and then presses Enter on his or her keyboard. However, I would like to also allow a user to type their query and then the click on the search icon and execute the search. If anyone can help me out would be greatly appreciated, I have listed all my relevant code below.
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
query = params[:q].presence || "*"
@booksearches = Book.search(query)
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 search_books_path, id:"searchform" do %>
<%= text_field_tag :q, nil, placeholder: "Search..." %>
<i class="fa fa-search" aria-hidden="true"></i>
<% end %>
</li>
</ul>
</div>
</nav>
</body>
After more research, i realized what I was missing was a simple submit-tag / submit type in my form. I have provided the code that worked for me below as well as an explanation in case anyone else stumbles like I did.
Steps 1: A form that does not include a submit tag or a button with a type equal to submit will default to the enter key being the submit action.
Step 2 (Submit Tag): If your using a submit button with words and no bootstrap icon - simply adding a submit tag would do the trick for you.
<%= submit_tag "Search", name: nill %>
Step 3:
If your using a bootstrap icon - then simply create a button and assign a type of submit to it.
<%= button_tag(type: "submit", class: "btn btn-default") do %>
<i class="fa fa-search" aria-hidden="true"></i>
<% end %>
My final code looked like this:
<%= form_tag search_books_path, id:"searchform" do %>
<%= text_field_tag :q, nil, placeholder:"Search..." %>
<%= button_tag(type: "submit", class: "btn btn-default") do %>
<i class="fa fa-search" aria-hidden="true"></i>
<% end %>
<% end %>