I\'m trying to install the twitter-typeahead-rails gem into my app. I\'ve followed several different tutorials but all of them result in errors.
Does an
Specify gem as dependency in your Gemfile:
# Gemfile
gem 'bootstrap-multiselect-rails'
Require typeahead files in your manifest:
// app/assets/javascripts/application.js
//= require twitter/typeahead
//= require twitter/typeahead/bloodhound
Javascript:
// app/assets/javascripts/models_controller.js
// initialize bloodhound engine
var bloodhound = new Bloodhound({
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
// sends ajax request to /typeahead/%QUERY
// where %QUERY is user input
remote: '/typeahead/%QUERY',
limit: 50
});
bloodhound.initialize();
// initialize typeahead widget and hook it up to bloodhound engine
// #typeahead is just a text input
$('#typeahead').typeahead(null, {
displayKey: 'name',
source: bloodhound.ttAdapter()
});
// this is the event that is fired when a user clicks on a suggestion
$('#typeahead').bind('typeahead:selected', function(event, datum, name) {
doSomething(datum.id);
});
View:
<-- app/views/models/whatever.html.erb -->
Routes:
# config/routes.rb
get 'typeahead/:query' => 'models#typeahead'
Controller:
# app/controllers/models_controller.rb
def typeahead
render json: Model.where(name: params[:query])
end
## note: the above will only return exact matches.
## depending on the database being used,
## something else may be more appropriate.
## here is an example for postgres
## for case-insensitive partial matches:
def typeahead
render json: Model.where('name ilike ?', "%#{params[:query]}%")
end
GET request to /typeahead/%QUERY returns json in the form of:
[
{
"name": "foo",
"id": "1"
},
{
"name": "bar",
"id": "2"
}
]