Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails implementation of search with autocomplete

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.

like image 675
Jseb Avatar asked Mar 03 '13 21:03

Jseb


1 Answers

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
   }
]);
like image 109
Alfonso Avatar answered Oct 27 '22 00:10

Alfonso