ruby on rails implement search with auto complete
- by user429400
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