加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Searchkick Bloodhound Typeahead用于自动完成

发布时间:2020-12-17 02:55:03 所属栏目:百科 来源:网络整理
导读:我正在尝试为单个属性实现一个简单的自动完成功能. 模型: searchkick text_start: [:name],autocomplete: ['name'] 重新编制Rails控制台上的行为索引后就可以了. 2.2.0-p0 :002 Doctor.search("a",autocomplete: true).map(:name) gives the output- = ["a"
我正在尝试为单个属性实现一个简单的自动完成功能.

模型:

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","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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读