I am at my wits end on this. I am trying to implement this tutorial for a global autocomplete search bar which searches the database for keywords typed and lists them. I have seen this question, and this, and this, and this, and several others. None has solved my issue.
The search query just does not return any results plus the autocomplete does not trigger. I, however, am still able to make calls to the function easyAutocomplete
as shown in the official guide. And I have no errors (at least on the surface).
Here are my code samples:
routes.rb:
Rails.application.routes.draw do
resources :photo_uploads
#......................
resources :posts do
put 'publish' => 'posts#publish', on: :member
put 'unpublish' => 'posts#unpublish', on: :member
end
get :search, controller: :posts
root to: 'static_pages#home'
get 'static_pages/about'
get 'static_pages/contact'
end
application_controller.rb:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :search
#.....................
def search
@q = Post.ransack(title_cont: params[:q])
@searchpost= @q.result(distinct: true)
# @bodysearch = Post.ransack(body_cont: params[:q]).result(distinct: true)
respond_to do |format|
format.html {}
format.json {
@searchpost = @searchpost.limit(6)
# @bodysearch = @bodysearch.limit(6)
}
end
end
end
erb file:
<%= search_form_for @q do |f| %>
<%= f.search_field :title_cont, class: " search-bar ml-3", data: { behavior: "autocomplete" } %>
<%= f.submit %>
<% end %>
search.json.jbuilder:
json.posts do
json.array!(@posts) do |post|
json.title post.title
json.url post_path(post)
json.published post.published_at
end
end
search.js:
document.addEventListener("turbolinks:load", function () {
$input = $("[data-behaviour='autocomplete']")
var options = {
getValue: "title",
url: function (phrase) {
return "/search.json?q=" + phrase;
},
categories: [
{
listlocation: "posts",
header: "<strong>Posts</strong>",
}
],
list: {
onChooseEvent: function () {
var url = $input.getSelectedItemData().url
$input.val("")
Turbolinks.visit(url)
}
}
}
$input.easyAutocomplete(options)
});
posts_controller.rb:
before_action :force_json, only: :search
# .............
private
def force_json
request.format = :json
end
I use the devise gem for authentication and cancancan for user roles/access. They work just fine. The rails version is 5.1.6
What am I doing wrong?