简体   繁体   中英

rails autocomplete searchkick

I'm trying to get an autocomplete working with typeahead.js

This is what i have at the moment.

This is in my controller.

  def autocomplete
    render json: Event.search(params[:query], autocomplete: true, limit: 10).map(&:eventname)
  end

This is in my routes

resources :events do
      collection do
        get :autocomplete
      end
    end

If i use the rails console and do this

Event.search("searchquery", autocomplete: true).map(&:eventname)

i do get the expected response,

However

If i search using the normal searchbox on my site i get this error

ActiveRecord::RecordNotFound (Couldn't find Event with 'id'=autocomplete):
  app/controllers/events_controller.rb:50:in `show'

On line 50 in the show (which is used elsewhere) is this

@event = Event.find(params[:id])

This is whats in my view

    <div class="col-md-12" align="center" style="padding-top: 1%">
      <%= javascript_include_tag "//cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.9.3/ typeahead.min.js" %>
    <h1><%= image_tag("Logo.png", :class => "logo", :style => "background-color: rgba(0, 0, 0, 0.8); border-radius: 50px") %></h1>
    <%= form_tag search_events_path, class: "form-inline form-wrapper", method: :get do %>
        <%= text_field_tag :search, params[:search], placeholder: "What are you looking for?", class: "search-module-input-text", id: "search", autocomplete: "off" %>
          <%= submit_tag "Search", id: "submit" %>
      </div>

I was trying to follow this tutorial

https://shellycloud.com/blog/2013/10/adding-search-and-autocomplete-to-a-rails-app-with-elasticsearch

I only got as far as adding the searchcode as you see above

Any help would be great!!!

Sam

edit

Heres the show part of the controller and the search part

  def search
    @events = Event.search params[:search], suggest: true, partial: true, misspellings: {distance: 4}
    if @events.results.any?
      render 'events/results'
    else
      render 'events/noresults'
    end
  end

  def show
    @event = Event.find(params[:id])
    @stubby = stub_auth_token
  end

rails console

curl http://localhost:9200/events_development/_search?pretty -d '{"query":{"multi_match":{"fields":["eventname.autocomplete"],"query":"response","analyzer":"searchkick_autocomplete_search"}},"size":1000,"from":0,"fields":[]}'
  Event Load (3.5ms)  SELECT "events".* FROM "events" WHERE "events"."id" IN (23419, 23420, 16330, 16329, 13660)
 => ["reponse1", "reponse2", "reponse3", "reponse4", "reponse5"]

你可以试试这个吗?

<%= form_tag autocomplete_events_path, ... %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM