![](/img/trans.png)
[英]RUBY ON RAILS: Why isn't typeahead autocomplete using searchkick/elasticsearch working?
[英]Searchkick + Bloodhound + Typeahead for autocomplete
我正在尝试为单个属性实现一个简单的自动完成功能 。
模型:
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
此时,如果我只是测试以下URL:
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控制台上也没有显示任何错误。
您需要返回哈希以响应自动完成操作:
def autocomplete
render json: Doctor.search(params[:query], autocomplete: true, limit: 10).map {|doctor| {name: doctor.name, value: doctor.id}}
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.