带有pg_search的Typeahead Bloodhound Rails

时间:2015-12-02 03:32:10

标签: javascript ruby-on-rails typeahead.js twitter-typeahead bloodhound

我正在使用此stackoverflow answer尝试为我的rails应用程序实现Twitter Typeahead,我也尝试实现Github自述文件,但是当我在文本框中输入时没有文字建议。< / p>

我的控制器

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
资产/ javascripts中的

pages_controller.js

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 %>

1 个答案:

答案 0 :(得分:1)

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

的CoffeeScript

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 %>