Search code examples
ruby-on-railsrubyelasticsearchtypeaheadsearchkick

Twitter Typeahead is is not showing suggestions in Rails 4


I have used elasticsearch with searchkick wrapper in my rails project. I have successfully integrated Twitter Typeahead (remote) into the project, but suggestions are not coming up. Can anybody Please look into this matter.

I am getting Response Back but typeahead is not showing it in suggestions.

Pictures Below

enter image description here


Response

enter image description here

controller :

def autocomplete
    render json: Product.search(params[:query], fuzziness: 10).map(&:name) 
end

index.html.erb :

    <%= form_tag products_path, method: :get do %>
  <ul>
    <li class="list">
      <%= text_field_tag :query, params[:query],placeholder: "Search Here", class: "typeahead form-control", id: "product-search", autocomplete: "off" %>
    </li>
    <li class="list">
      <%= submit_tag "Search", class: "btn btn-primary btn-size" %>
    </li>
      </ul>
<% end %>

products.js

 var names = new Bloodhound({
  datumTokenizer: function(d) { 
    return Bloodhound.tokenizers.whitespace(d.name); },
  queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
      url: '/products/autocomplete?query=%QUERY',
      wildcard: '%QUERY'
    }
  });

  // initialize the bloodhound suggestion engine
  names.initialize();

  // instantiate the typeahead UI
  $('#product-search').typeahead(null, {
  displayKey: 'name',
  source: names.ttAdapter()
});

Solution

  • I am not working with a typeahead lib, but i assume the problem here displayKey: 'name', what's mean an autocomplete action in the rails should provide json with a key name, but you render an array. Try to remove .map(&:name) from Product.search(params[:query], fuzziness: 10).