Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 753
user429400 Avatar asked Jun 10 '26 23:06

user429400


1 Answers

I have had the same problem and had to create this gem for it: https://github.com/rayasocialmedia/rails_autocomplete

like image 189
Omar Ali Avatar answered Jun 13 '26 17:06

Omar Ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!