自动完成结果在Rails中的Typeahead中显示为undefined

时间:2015-07-12 17:01:40

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

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

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,Bangalore”},{“location”:“RT Nagar,Bangalore”},{“location”:“RT Nagar,Kolkata”}]

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

1 个答案:

答案 0 :(得分:1)

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

"example"

并通过

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

现在我将结果显示在下拉列表中,并获得搜索结果。感谢大家。如果有其他建议,请写信。