简体   繁体   中英

ruby on rails implement search with auto complete

I've implemented a search box that searches the "Illnesses" table and the "symptoms" table in my DB. Now I want to add auto-complete to the search box.

I've created a new controller called "auto_complete_controller" which returns the auto complete data. I'm just not sure how to combine the search functionality and the auto complete functionality: I want the "index" action in my search controller to return the search results, and the "index" action in my auto_complete controller to return the auto_complete data.

Please guide me how to fix my html syntax and what to write in the js.coffee file. I'm using rails 3.x with the jquery UI for auto-complete, I prefer a server side solution, and this is my current code:

main_page/index.html.erb:

<p>
    <b>Syptoms / Illnesses</b>
    <%= form_tag search_path, :method => 'get' do %>
      <p>
        <%= text_field_tag :search, params[:search] %> <br/>

        <%= submit_tag "Search", :name => nil %>
      </p>
  <% end %>
</p>

auto_complete_controller.rb:

class AutoCompleteController < ApplicationController

    def index
    @results = Illness.order(:name).where("name like ?", "%#{params[:term]}%") + Symptom.order(:name).where("name like ?", "%#{params[:term]}%")

    render json: @results.map(&:name)
  end
end

search_controller.rb:

class SearchController < ApplicationController

def index
    @results = Illness.search(params[:search]) + Symptom.search(params[:search])

    respond_to do |format|
        format.html # index.html.erb
        format.json { render json: @results }
    end
 end
end

Thanks, Li

我有同样的问题,不得不为它创建这个宝石: https//github.com/rayasocialmedia/rails_autocomplete

Here's how to do dynamic typeahead in Twitter-Bootstrap; I'm sure it's something similar for jQuery:

https://gist.github.com/1848558

Essentially, by listening to to non-navigational keystrokes, it triggers an AJAX partial text search to your controller. This return data then populates the JS framework's typeahead/autocomplete data to be displayed. This means that you really only need the one SearchController.

Try rails3-jquery-autocomplete . I am using it and had the same requirements as you, and they work fine together. Let me know if you need further help.

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