Avijit Majhi
Avijit Majhi

Reputation: 518

AutoComplete result shows undefined in Typeahead in Rails

I am using searchkick gem for elastic search,typeahead for autocomplete.I have a Model Store with column like location,city,store_name etc.I want to show the location and city in autocomplete dropdown.My model code is

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

My controller is

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

My view code is

<%= 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 %>

and my store.js.coffee

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

when I search ,it returns result like [{"location":"RT Nagar , Bangalore"},{"location":"RT Nagar , Bangalore"},{"location":"RT Nagar , Kolkata"}]

I want to show the result in autocomplete dropdown list.Please suggest me how should I write search to get exact results.

Upvotes: 1

Views: 392

Answers (1)

Avijit Majhi
Avijit Majhi

Reputation: 518

I solve this another way,now my controller code look like

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

and searching is done by

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

Now I get the result in dropdown,and also get search results.Thank You everyone.If another suggestion is possible then please write.

Upvotes: 1

Related Questions