简体   繁体   中英

Searchkick + Bloodhound + Typeahead for autocomplete

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

Model:

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

After reindexing the behaviour on the Rails console is ok .

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

After this i added the Autocomplete action to the controller and a new route to the routes.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 simply 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 adding 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 the 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 this is the script tag used:

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

There is no response shown by the search box on typing anything,also there is no error shown on the console of Google Chrome.

You need to return hash in response of your autocomplete action:

def autocomplete
  render json: Doctor.search(params[:query], autocomplete: true, limit: 10).map {|doctor| {name: doctor.name, value: doctor.id}}
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