Rails implementation of search with autocomplete

13,820

Use Twitter typeahead. There are some examples here:

http://twitter.github.com/typeahead.js/examples/

Twitter typeahead and all the information you need is available from https://github.com/twitter/typeahead.js/

How to use

The use depends on the data you are going to have as 'suggested'. For example, if it is static data (always going to be the same) you can implement it this way:

$('input.typeahead').typeahead({
  local: ['suggestion1', 'suggestion2', 'suggestion3',...., 'suggestionN']
  #The typeahead is going to load suggestions from data in local.
});

If the data changes and it came from a model or a db table then you can try:

Controller:
def load_suggestions
  @suggestions = MyModel.select(:name) or MyModel.find(:all, conditions: [...]) #Select the data you want to load on the typeahead.
  render json: @suggestions
end

JS file:
$('input.typeahead').typeahead([
  {
    prefetch: 'https://www.mipage.com/suggestion.json' #route to the method 'load_suggestions'
    #This way, typeahead will prefecth the data from the remote url
   }
]);
Share:
13,820
Jseb
Author by

Jseb

Updated on August 02, 2022

Comments

  • Jseb
    Jseb over 1 year

    I am not to sure how to have an autocomplete form to my search function.

    <%= form_tag "/search", :method => "get" do %>
        <%= text_field_tag :query, params[:query] %>
        <%= image_submit_tag "site/blankimg.png", :name => nil %>
    <% end %>
    

    I have a controller of the following which has a customized action

       def query
         @users= Search.user(params[:query])
         @article= Search.article(params[:query])
       end
    

    The model is has follow:

    def self.user(search)
     if search
        User.find(:all, :conditions => ['first_name LIKE ?', "%#{search}%"])
      else
        User.find(:all)
      end
    end
    
    def self.article(search)
      if search
        Article.find(:all, :conditions => ['title LIKE ?', "%#{search}%"])
      else
        Article.find(:all)
      end
    end
    

    Now this work great for a search but it, i would like it to show me the result has i am writing it, and i can't use jquery autocomplete because it is two object.

  • Jseb
    Jseb about 11 years
    how would i hook my model to it?
  • Jseb
    Jseb about 11 years
    thanks, i am reading their api is a bit confusing for first time seen
  • Alfonso
    Alfonso about 11 years
    You have to download both typeahead.js and typeahead.css files
  • laimison
    laimison about 7 years
    Can you confirm gem for Rails 4? Is it bootstrap-typeahead-rails? So having simple <input class="typeahead"... in views and gem asset enabled should be enough? If I type sugg I should be able to see all options: suggestion1, suggestion2, etc.?