预先输入重复记录

时间:2018-04-04 09:30:40

标签: javascript ruby-on-rails typeahead.js typeahead

我在我的rails应用中使用typeahead,如下所示:

<%= form_tag search_path, :method => "get", id: "search-form" do %>
  <%= text_field_tag :search, params[:search], id: "search" %>
  <%= submit_tag "Search" %>
<%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>

控制器动作:

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

自动填充功能正常,但显示重复结果。任何想法如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

正如@danny基本建议的那样,在地图之后使用.uniq

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