我对此事不知所措。我正在尝试为全局自动完成搜索栏实现this tutorial,该搜索栏在数据库中搜索键入的关键字并列出它们。我看过this question,this,this,this以及其他几个。没有人解决了我的问题。
搜索查询仅不返回任何结果,并且不触发自动完成。但是,我仍然可以按easyAutocomplete
所示调用函数official guide。而且我没有错误(至少从表面上看)。
这是我的代码示例:
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文件:
<%= 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
我使用devise gem进行身份验证,并使用cancancan进行用户角色/访问。他们工作得很好。 rails版本是5.1.6
我在做什么错?
这可能有点晚了,但是我也在尝试遵循本教程,并且遇到了类似的问题。对我来说,我使用的是Rails 6和webpacker,必须确保用于easyautocomplete的js和css文件位于资产管道中,并且已正确链接。然后,一旦我使webpacker能够正确编译,搜索栏便开始工作。