In Rails, how to set up Twitter Typeahead.js tag for Rails?

bootstrap-typeahead-railsgem README puts a question on Twitter typeahead.js README . This left much to be desired.

This stack overflow answer contains detailed instructions for twitter-typeahead-railsgem , I wanted to see something similar for a gem bootstrap-typeahead-rails.

+4
source share
2 answers

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

# Gemfile

# Typeahead gem
gem 'bootstrap-typeahead-rails'

# Optional gems
gem 'searchlight'
gem 'slim-rails'

(SASS)

# app/assets/stylesheets/application.scss

  *= require bootstrap-typeahead-rails

Javascript

# app/assets/javascripts/application.js

//= require bootstrap-typeahead-rails
//= require_tree .

typeahead

# config/routes.rb

  get 'things/typeahead/:query' => 'things#typeahead'

javascript- ahead

# app/assets/javascripts/things.js

var onReady = function() {

  // initialize bloodhound engine
  var searchSelector = 'input.typeahead';

  var bloodhound = new Bloodhound({
    datumTokenizer: function (d) {
      return Bloodhound.tokenizers.whitespace(d.value);
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,

    // sends ajax request to remote url where %QUERY is user input
    remote: '/things/typeahead/%QUERY',
    limit: 50
  });
  bloodhound.initialize();

  // initialize typeahead widget and hook it up to bloodhound engine
  // #typeahead is just a text input
  $(searchSelector).typeahead(null, {
    displayKey: 'name',
    source: bloodhound.ttAdapter()
  });

  // this is the event that is fired when a user clicks on a suggestion
  $(searchSelector).bind('typeahead:selected', function(event, datum, name) {
    //console.debug('Suggestion clicked:', event, datum, name);
    window.location.href = '/things/' + datum.id;
  });
};

/

# app/controllers/things_controller.rb

  # GET /things
  # GET /things.json
  def index
    @search = ThingSearch.new(search_params)
    @things = search_params.present? ? @search.results : Thing.all
  end

  # GET /things/typeahead/:query
  def typeahead
    @search  = ThingSearch.new(typeahead: params[:query])
    render json: @search.results
  end

  private

  def search_params
    params[:thing_search] || {}
  end

( SLIM)

# app/views/things/index.html.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 .

# app/searches/thing_search.rb

class ThingSearch < Searchlight::Search
  search_on Thing.all

  searches :name_like, :typeahead

  # Note: these two methods are identical but they could reasonably differ.
  def search_name_like
    search.where("name ILIKE ?", "%#{name_like}%")
  end

  def search_typeahead
    search.where("name ILIKE ?", "%#{typeahead}%")
  end
end
+11

@klenwell . :

:

  • Bootstrap v3.3.6
  • bloodhound 0.11.1
  • bootstrap3-typeahead 3.1.0
  • jQuery 2.2.0

Destination.

//destination_search.rb:

class DestinationSearch < Searchlight::Search

  def base_query
    Destination.all
  end

  def search_typeahead
    query.where("name ILIKE", "%#{typeahead}%")
  end

end

:

class DestinationsController < APIController

  def typeahead
    render json: DestinationSearch.new(typeahead: params[:query]).results
  end

end

JS:

var bloodhound = new Bloodhound({
  datumTokenizer: function (d) {
    return Bloodhound.tokenizers.whitespace(d.value);
  },
  queryTokenizer: Bloodhound.tokenizers.whitespace,

  remote: {
    url: '/api/destinations/typeahead?query=%QUERY',
    wildcard: "%QUERY",
  },
  limit: 10
});
bloodhound.initialize();

$(document).ready(function () {
  $(".destination-typeahead").typeahead({
    source: function (query, process) {
      return bloodhound.search(query, process, process);
    },
  });
});

:

<%= text_field_tag :destination, class: "destination-typeahead" %>

, process bloodhound.search - , bloodhound # search , / , , AJAX. , #search 100% , , .

+2

All Articles