Searchkick + Bloodhound + Typeahead for autocomplete

I am trying to implement a simple autocomplete function for a single attribute.

Model:

searchkick text_start: [:name],autocomplete: ['name']

After overriding, the behavior on the Rails console is fine .

2.2.0-p0 :002 >Doctor.search("a", autocomplete: true).map(&:name) 
gives the output-
 => ["a", "aa", "aaa", "aaaa"] 

After that, I added the Autocomplete action to the controller and a new route to the route.rb file.

Controller:

def autocomplete
    console.log("In auto")
    render json: Doctor.search(params[:query], autocomplete: false, limit: 10).map(&:name)
  end

Routes

resources :doctors do
    collection do
      get :autocomplete
    end
  end

At this point, if I just test the following URL:

http://localhost:3000/doctors/autocomplete?query="a"

Then I get the expected result in the browser :

["a", "aa", "aaa", "aaaa"] 

Now add a search box.

_header.html.erb:

  <%= form_tag doctors_path, method: :get do %>
    <div class="form-group">
      <%= text_field_tag :query, params[:query], class: 'form-control typeahead', autocomplete: "off" %>
      <%= submit_tag 'Search', class: 'btn btn-primary' %>
    </div>
  <% end %>

And finally, Javascript:

var ready;
ready = function() {
    var numbers = new Bloodhound({
      remote: {url: "/doctors/autocomplete?query=%QUERY"},
      datumTokenizer: function(d) { 
              return Bloodhound.tokenizers.whitespace(d.name); },
      queryTokenizer: Bloodhound.tokenizers.whitespace


});

// initialize the bloodhound suggestion engine

var promise = numbers.initialize();

promise
.done(function() { console.log('success!'); })
.fail(function() { console.log('err!'); });

// instantiate the typeahead UI
$( '.typeahead').typeahead(null, {
  displayKey: 'name',
  source: numbers.ttAdapter()
});
}

$(document).ready(ready);
$(document).on('page:load', ready);

And the script tag is used:

<script type="text/javascript" src="https://twitter.imtqy.com/typeahead.js/releases/latest/typeahead.bundle.js"></script>

There is no answer in the search box, typing anything, also there is no error displayed on the Google Chrome console.

+4
1

:

def autocomplete
  render json: Doctor.search(params[:query], autocomplete: true, limit: 10).map {|doctor| {name: doctor.name, value: doctor.id}}
end
+5

All Articles