Searchkick, typeahead.js and Elasticsearch
I am trying to implement an autocomplete search bar that searches for posts in my Rails 4.2 application. I have elasticsearch installed, searchkick gem and typeahead.js for autocomplete on frontend.
To this end, I followed the tutorial ( https://shellycloud.com/blog/2013/10/adding-search-and-autocomplete-to-a-rails-app-with-elasticsearch ) and created the following settings:
In mine, routes.rb
I configured the collection route as follows:
resources :posts do
collection do
get :autocomplete
end
resources :attachments
end
In my model Post.rb
:
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 opinion 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 enter something in the search box, I get this:
GET XHR http://localhost/posts/autocomplete [HTTP/1.1 400 Bad Request 177ms]
I cannot tell what is going on. For what it's worth, I tried to push http://localhost/posts/autocomplete.json?query=something
and it works in that it will return the result of the match. I also tried replacing autocomplete
with autocomplete.json
in the JS posted above.
However, I am getting the same error in the console (with autocomplete.json
instead of autocomplete
)
You can help?
source to share
No one has answered this question yet
Check out similar questions: