Rails implementation of search with autocomplete
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
}
]);
Jseb
Updated on August 02, 2022Comments
-
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 about 11 yearshow would i hook my model to it?
-
Jseb about 11 yearsthanks, i am reading their api is a bit confusing for first time seen
-
Alfonso about 11 yearsYou have to download both typeahead.js and typeahead.css files
-
laimison about 7 yearsCan 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 typesugg
I should be able to see all options:suggestion1
,suggestion2
, etc.?