Searchkick, typeahead.js and Elasticsearch issues

361 views Asked by At

I am trying to implement an autocomplete search bar that searches posts in my Rails 4.2 app. I have elasticsearch installed, searchkick gem, and typeahead.js for autocomplete on the frontend.

To that end, I followed a tutorial (https://shellycloud.com/blog/2013/10/adding-search-and-autocomplete-to-a-rails-app-with-elasticsearch) and have the following things set up:

In my routes.rb I have set up the collection route like so:

 resources :posts do
   collection do
     get :autocomplete
   end
   resources :attachments 
 end

In my Post.rb model:

searchkick autocomplete: ['title', 'excerpt']

In my posts_controller.rb

def index
  if params[:query].present?
    @posts = Post.search(params[:query])
  end  
end

def autocomplete
   render json: Post.search(params[:query], autocomplete: true, limit: 10).map do |post|
   {title:post.title, excerpt: post.excerpt}
  end
end

In my posts.js

$(document).ready(function() {
   var posts = new Bloodhound({
       datumTokenizer: Bloodhound.tokenizers.obj.whitespace('title'),
       queryTokenizer: Bloodhound.tokenizers.whitespace,
       prefetch: "/posts/autocomplete?query=%QUERY",
   remote: {
       url: "/posts/autocomplete?query=%QUERY"
   }
 });

$('#query').typeahead({
  name: 'posts',
  display: 'title',
  source: posts
});
})

Finally, in my view index.html.haml I have:

=form_tag(posts_path, method: :get) do
  =text_field_tag(:query, params[:query], autocomplete: 'off', class: 'typeahead')
  %input{:type=>"submit", :value=> t('search')}

When I type something in the search box, I get this:

GET XHR http://localhost/posts/autocomplete [HTTP/1.1 400 Bad Request 177ms]

I can't tell what is going on. For what its worth, I have tried hitting http://localhost/posts/autocomplete.json?query=something and it works in that it will return the matching result. I have also tried replacing autocomplete with autocomplete.json in the JS I posted above.

Still, I get the same error in the console (with autocomplete.json in place of autocomplete)

Can you help?

0

There are 0 answers