Searchkick and typeahead search dropdown suggestion is not working in Rails App

210 Views Asked by At

I am trying to build a very simple rails application where i want to search properties by the title. I want that the input field should suggest me matched properties as dropdown so that I can select.

Model: property.rb

 class Property < ApplicationRecord
   searchkick word_start: [:title]

   def search_data
   {
    title: title
   }
  end
end

Controller: 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
});

})

Search Form:

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

Search is Okay, but the dropdown suggestion is not working. I Just want the dropdown list to be suggested from the matched title of properties. dropdown

1

There are 1 best solutions below

0
On

Finally I have found the solution by myself. Actually, I was searching the property from the root path but the JSON response was created in the properties path. So, I search from the Properties#Index and it works fine.