Searchkick + Bloodhound + Typeahead用于自动完成

时间:2015-02-22 03:21:10

标签: ruby-on-rails elasticsearch typeahead.js bloodhound searchkick

我正在尝试为单个属性实施简单自动完成功能

型号:

searchkick text_start: [:name],autocomplete: ['name']

重新编制 Rails控制台上的行为索引后

2.2.0-p0 :002 >Doctor.search("a", autocomplete: true).map(&:name) 
gives the output-
 => ["a", "aa", "aaa", "aaaa"] 

在此之后,我将自动完成操作添加到控制器,并将新路由添加到routes.rb文件。

控制器:

def autocomplete
    console.log("In auto")
    render json: Doctor.search(params[:query], autocomplete: false, limit: 10).map(&:name)
  end

路线:

resources :doctors do
    collection do
      get :autocomplete
    end
  end

此时如果我只测试以下网址:

http://localhost:3000/doctors/autocomplete?query="a"

然后我在浏览器中获得预期结果

["a", "aa", "aaa", "aaaa"] 

现在添加一个搜索框。

_header.html.erb:

  <%= form_tag doctors_path, method: :get do %>
    <div class="form-group">
      <%= text_field_tag :query, params[:query], class: 'form-control typeahead', autocomplete: "off" %>
      <%= submit_tag 'Search', class: 'btn btn-primary' %>
    </div>
  <% end %>

最后是Javascript:

var ready;
ready = function() {
    var numbers = new Bloodhound({
      remote: {url: "/doctors/autocomplete?query=%QUERY"},
      datumTokenizer: function(d) { 
              return Bloodhound.tokenizers.whitespace(d.name); },
      queryTokenizer: Bloodhound.tokenizers.whitespace


});

// initialize the bloodhound suggestion engine

var promise = numbers.initialize();

promise
.done(function() { console.log('success!'); })
.fail(function() { console.log('err!'); });

// instantiate the typeahead UI
$( '.typeahead').typeahead(null, {
  displayKey: 'name',
  source: numbers.ttAdapter()
});
}

$(document).ready(ready);
$(document).on('page:load', ready);

这是使用的脚本标记:

<script type="text/javascript" src="https://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>

搜索框中没有显示任何关于输入内容的响应,Google Chrome控制台上也没有显示任何错误。

1 个答案:

答案 0 :(得分:5)

您需要返回哈希以响应自动完成操作:

def autocomplete
  render json: Doctor.search(params[:query], autocomplete: true, limit: 10).map {|doctor| {name: doctor.name, value: doctor.id}}
end