Here is my guide. This follows the example of @ihaztehcodez . This example assumes a model Thingand adds the form to the index view for searching thingsusing the model attribute name.
A few notes:
- I am using Rails 4 (4.2.1).
- .
- .
- .
gem gemfile
gem 'bootstrap-typeahead-rails'
gem 'searchlight'
gem 'slim-rails'
(SASS)
*= require bootstrap-typeahead-rails
Javascript
# app/assets/javascripts/application.js
typeahead
# config/routes.rb
get 'things/typeahead/:query' => 'things#typeahead'
javascript- ahead
var onReady = function() {
var searchSelector = 'input.typeahead';
var bloodhound = new Bloodhound({
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: '/things/typeahead/%QUERY',
limit: 50
});
bloodhound.initialize();
$(searchSelector).typeahead(null, {
displayKey: 'name',
source: bloodhound.ttAdapter()
});
$(searchSelector).bind('typeahead:selected', function(event, datum, name) {
window.location.href = '/things/' + datum.id;
});
};
/
def index
@search = ThingSearch.new(search_params)
@things = search_params.present? ? @search.results : Thing.all
end
def typeahead
@search = ThingSearch.new(typeahead: params[:query])
render json: @search.results
end
private
def search_params
params[:thing_search] || {}
end
( SLIM)
div.search.things
= form_for @search, url: things_path, method: :get do |f|
div.form-group.row
div.col-sm-3
div.col-sm-6
= f.text_field :name_like, {class: 'typeahead form-control',
placeholder: "Search by name"}
= f.submit 'Search', {class: 'btn btn-primary'}
div.col-sm-3.count
| Showing <strong>#{@things.length}</strong> Thing#{@things.length != 1 ? 's' : ''}
Searchlight
, ActiveRecord .
class ThingSearch < Searchlight::Search
search_on Thing.all
searches :name_like, :typeahead
def search_name_like
search.where("name ILIKE ?", "%#{name_like}%")
end
def search_typeahead
search.where("name ILIKE ?", "%#{typeahead}%")
end
end