【问题标题】:Searchkick and typeahead search dropdown suggestion is not working in Rails AppSearchkick 和 typeahead 搜索下拉建议在 Rails 应用程序中不起作用
【发布时间】:2021-12-18 06:02:37
【问题描述】:

我正在尝试构建一个非常简单的 Rails 应用程序,我想在其中按标题搜索属性。我希望输入字段应该建议我匹配的属性作为下拉列表,以便我可以选择。

型号:property.rb

 class Property < ApplicationRecord
   searchkick word_start: [:title]

   def search_data
   {
    title: title
   }
  end
end

控制器:properties_controller.rb

class PropertiesController < ApplicationController

  def index
    search = params[:term].present? ? params[:term] : nil
    @properties = if search
     Property.search(search)
    else
      Property.all
    end
  end

 def autocomplete
  render json: Property.search(params[:query], {
  fields: ["titleˆ5"],
  match: :word_start,
  limit: 10,
  load: false,
  misspellings: {below: 5}
 }).map(&:title)
end

JavaScript:properties.js

$(document).on('turbolinks:load', function(){
  var properties = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.whitespace,
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  remote: {
    url: '/properties/autocomplete?query=%QUERY',
    wildcard: '%QUERY'
  }
});
$('#properties_search').typeahead(null, {
  source: properties
});

})

搜索表格:

   <%= form_tag(root_path, method: :get, class: "form-inline", role: 'search') do %>
    <div class="input-group">              
      <%= text_field_tag :term, 
          params[:term], 
          id: 'properties_search', 
          autocomplete: :off, 
          placeholder: 'Search', 
          class: 'form-control' %>
      <div class="input-group-btn search-panel">
        <%= link_to 'Clear', root_url, class: "btn btn-default" %>
        <%= submit_tag 'Search', name: nil, class: "btn btn-default" %>
      </div>
    </div>
  <% end %>

搜索没问题,但下拉建议不起作用。 我只想从匹配的属性标题中建议下拉列表。

【问题讨论】:

    标签: ruby-on-rails ruby searchkick twitter-typeahead typehead


    【解决方案1】:

    终于我自己找到了解决方案。实际上,我正在从根路径搜索属性,但 JSON 响应是在属性路径中创建的。所以,我从 Properties#Index 中搜索,它工作正常。

    【讨论】:

      最近更新 更多