首页 > 解决方案 > Rails:typeahead.js 下拉列表返回重复项或已删除的对象

问题描述

我已经typeahead.js在我的 Rails 应用程序上安装了,但是当我开始在输入字段中输入一个单词时,下拉列表会返回重复项或被删除的对象以及正确的单词。

这是我的设置:

控制器内部:

def autocomplete
 render json: Item.search(params[:search], {
    fields: ["title"],
    match: :word_start,
    limit: 10,
    load: false,
    misspellings: {below: 5}
 }).map(&:title).uniq
end

在视图内部:

<script>
var items = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.whitespace,
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: '/items/autocomplete?search=%SEARCH',
        wildcard: '%SEARCH'
    }
});


$('#search')
    .typeahead(null, {source: items})
    .on('typeahead:selected', function(e){
        $("#search-form").submit();
    }).focus();
</script>

知道如何解决这个问题吗?

更新 1

如果我在 rails 控制台内执行此操作,它会返回一个空数组,这是正确的,因为目前我在数据库中没有项目。但是,如果在输入字段中键入已删除的旧项目,则会出现在下拉列表中:

2.4.0 :026 > Item.all.map(&:title).uniq
  Item Load (0.4ms)  SELECT "items".* FROM "items"
=> [] 

标签: javascriptruby-on-railstypeahead.jstypeahead

解决方案


推荐阅读