【问题标题】:AutoComplete result shows undefined in Typeahead in Rails自动完成结果在 Rails 中的 Typeahead 中显示未定义
【发布时间】:2015-09-30 22:43:19
【问题描述】:

我正在使用 searchkick gem 进行弹性搜索,预先输入以进行自动完成。我有一个模型商店,其中包含位置、城市、商店名称等列。我想在自动完成下拉列表中显示位置和城市。我的模型代码是

class Store < ActiveRecord::Base
  searchkick autocomplete: ['location','city'], 
         suggest: ['location','city']
  attr_accessible :city, :location, :name, :pincode
end

我的控制器是

class StoresController < ApplicationController
   # GET /stores
   # GET /stores.json
   def index
     if params[:query].present?
       @stores = Store.search(params[:query],fields: [:location,:city])
     else
       @stores = Store.all
     end
     respond_to do |format|
       format.html # index.html.erb
       format.json { render json: @stores }
     end
   end

   def autocomplete
      render json: Store.search(params[:query], autocomplete: true,fields: [:location,:city], limit: 10).map {|store|
    {location: "#{store.location} , #{store.city}"}}
   end
end

我的查看代码是

<%= form_tag stores_path, class: "form-inline", method: :get do %>
     <div class="input-group input-group-lg">
        <% if params[:query].present? %>
           <div class="input-group-btn">
              <%= link_to "clear", stores_path, class: "btn btn-default" %>
           </div>
        <% end %>
        <%= text_field_tag :query, params[:query], class: "form-control typeahead", id: "store_search", autocomplete: "off" %>
            <div class="input-group-btn">
               <%= submit_tag "Search", class: "btn btn-primary" %>
            </div>
      </div>
 <% end %>

还有我的 store.js.coffee

$ ->
    $('#store_search').typeahead
        name: "store",
        displayKey: 'location',
        remote: "/stores/autocomplete?query=%QUERY"

当我搜索时,它会返回类似的结果 [{"location":"RT Nagar , 班加罗尔"},{"location":"RT Nagar , 班加罗尔"},{"location":"RT Nagar , 加尔各答"}]

我想在自动完成下拉列表中显示结果。请建议我应该如何编写搜索以获得准确的结果。

【问题讨论】:

    标签: jquery ruby-on-rails elasticsearch autocomplete typeahead.js


    【解决方案1】:

    我用另一种方式解决了这个问题,现在我的控制器代码看起来像

    def autocomplete
        render json: Store.search(params[:query], autocomplete: true,fields: [:location,:city], limit: 10).map {|store|
        "#{store.location},#{store.city}"}
    end
    

    搜索由

    完成
    def index
       if params[:query].present?
         @location,@city = params[:query].split(',')
         @stores = Store.search(@location,where: {city: @city},fields:   [:location,:city])
       else
         @stores = Store.all
       end
       respond_to do |format|
         format.html # index.html.erb
         format.json { render json: @stores }
       end
    end
    

    现在我在下拉列表中得到结果,也得到搜索结果。谢谢大家。如果有其他建议,请写。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-07
      • 1970-01-01
      • 1970-01-01
      • 2012-03-24
      相关资源
      最近更新 更多