When I use autocompleted search form in some pages it is working but for when I click the "Home", "Help" or "Users" links on navbar, I can only use search form without autocompleted feature.
layouts/header.html.erb
<% if logged_in? %>
<%= form_tag users_path, class: "navbar-form navbar-left", method: :get do %>
<% if params[:query].present? %>
<%= link_to "clear", users_path%>
<%end%>
<div class="input-group input-group-md">
<%= text_field_tag :query, params[:query], class: "form-control",id: "user_search", autocomplete: "off",:placeholder => "Find other users" %>
</div>
<button type="submit" class="btn btn-default">Search</button>
<% end %>
<%end%>
<nav>
<ul class="nav navbar-nav navbar-right">
<li><%= link_to "Home", root_path %></li>
<li><%= link_to "Help", help_path %></li>
<% if logged_in? %>
<li><%= link_to "Users", users_path %></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
Account <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><%= link_to "Profile", current_user %></li>
<li><%= link_to "Settings", edit_user_path(current_user) %></li>
<li class="divider"></li>
<li>
<%= link_to "Log out", logout_path, method: "delete" %>
</li>
</ul>
</li>
<% else %>
<li><%= link_to "Log in", login_path %></li>
<% end %>
</ul>
</nav>
</div>
</header>
User model
searchkick autocomplete: ['name']
users_controller
def index
if params[:query].present?
@users = User.search(params[:query], page: params[:page])
else
@users = User.all.page params[:page]
end
end
def autocomplete
render json: User.search(params[:query], autocomplete: true, limit: 10).map(&:name)
end
application.html.erb
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= javascript_include_tag "//cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.9.3/typeahead.min.js" %>
users.js.coffee
$ ->
$('#user_search').typeahead
name: "user"
remote: "/users/autocomplete?query=%QUERY"
routes.rb
resources :users do
collection do
post :import
get :autocomplete # <= add this line
end
root to: 'users#index'
member do
get :following, :followers
end
end