Typeahead Bloodhound Rails 和 pg_search

Typeahead Bloodhound Rails with pg_search

我正在使用这个 Whosebug to try and implement Twitter Typeahead for my rails app and I have also tried implementing the Github 自述文件,但是当我在文本框中键入时没有文本建议。

我的控制器

class PagesController < ApplicationController
  def typeahead

    @vn = Vn.search_by_name(params[:search])
    render json: @vn.results
  end
end

我的路线

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

Application.js

//= require twitter/typeahead
//= require twitter/typeahead/bloodhound

pages_controller.js 在 assets/javascripts

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);
});

我的观点

   <%= form_tag(search_path, :method => "get", class: "navbar-form", id: "search-form") do %>
      <%= text_field_tag :search, params[:search], class: "form-control padding-search typeahead", placeholder: "Search" %>   
      <%= button_tag(type: "submit", class: "btn btn-primary padding-search") do %>          
   <% end %>

这是允许 Typeahead 建议在经过一段时间的故障排除后为我工作的设置。

咖啡脚本

jQuery -> 
  users = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.whitespace,
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  limit: 10,
  #local http://localhost:3000/json/vns.json
  remote: {url:'/typeahead/%QUERY'
   , wildcard: '%QUERY'
   }
  })

  users.initialize();
  $('.typeahead').typeahead(null, {
      name: "mysearch"
      source: users.ttAdapter()
  })

控制器

    def typeahead    
    @vn = Vn.search_by_name(params[:search])
    @name = @vn.select('name').map(&:name)

    render json: @name
  end
  //Under Routes
  get 'typeahead/:search' => 'pages#typeahead'
  //View
 <%= form_tag(search_path, :method => "get", class: "navbar-form", id: "search-form" ) do %>
              <%= text_field_tag :search, params[:search], class: "form-control typeahead", placeholder: "Search " %>
              <%= button_tag(type: "submit", class: "btn btn-primary padding-search") do %>
                  <i class="fa fa-search 6x"></i>
              <% end %>
 <% end %>