A working twitter-typeahead example?

I am trying to install a gem twitter-typeahead-railsin my application. I have followed several different tutorials, but all of them lead to errors.

Does anyone have a working example of this gem?

+4
source share
2 answers

Define a pearl as a dependency in your Gemfile:

# Gemfile

gem 'bootstrap-multiselect-rails'

Require head type 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 -->

<input type="text" id="typeahead">

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

A GET request in / typeahead /% QUERY returns json in the form:

[
  {
    "name": "foo",
    "id": "1"
  },
  {
     "name": "bar",
     "id": "2"
  }
]
+9
source

The accepted answer is not entirely correct.

It seems that two different stones do about the same thing:

bootstrap-multiselect-rails 0.9.9 , . :

In application.js:
//= require bootstrap-multiselect

In application.css:
*= require bootstrap-multiselect

Git: https://github.com/benjamincanac/bootstrap-multiselect-rails

twitter-typeahead-rails, 0.11.1, , , , .

Git: https://github.com/yourabi/twitter-typeahead-rails

5-6 .

, URL-, Bloodhound JS, :

remote: '/typeahead/%QUERY'

remote: {url: '/typeahead/%QUERY', wildcard: '%QUERY'}

, -

+5

All Articles