基于上面的答案,这个 和这个
什么工作如下所示:
def autocomplete
names = Doctor.search(params[:query], fields: [{name: :text_start}], limit: 10).map {|Doctor| {store: doctor.name, value: doctor.id}}
collegenames = Doctor.search(params[:query], fields: [{collegename: :text_start}], limit: 10).map {|Doctor| {store: doctor.collegename, value: doctor.id}}
render json: (names + collegenames)
end
变量 store: 现在包含所有数据。
Javascript:
var ready;
ready = function() {
console.log("dfdf")
var numbers = new Bloodhound({
datumTokenizer: function(d) {
console.log(d);
return Bloodhound.tokenizers.whitespace('value');
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url:"/doctors/autocomplete?query=%QUERY"
}
});
// 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: 'store',
source: numbers.ttAdapter()
});
}
$(document).ready(ready);
$(document).on('page:load', ready);
自动完成功能在这两个领域都很好,但是现在我在写一个像这样的 url 时得到一个空数组
http://localhost:3000/doctors/autocomplete?query="a"