让 typeahead 与 rails 搜索一起使用

Getting typeahead to work with rails search

我在我的 rails 4 应用程序中使用 typeahead v0.10.5 进行了预输入和搜索,但自从更新到 v0.11.1 后它就坏了。我最初从这个网站上的各种答案中获得了代码,但并没有真正理解发生了什么。我现在大部分时间都在使用它,但是下拉列表中填充了我模型中所有属性的文本,而不仅仅是我想要的名称。我想确保自己做事正确,并希望能更好地了解正在发生的事情。

item.rb

  def self.search(search)
    if search
      where(['lower(name) LIKE ?', "%#{search}%"])
    else
      Item.all
    end
  end

items_controller.rb

  def index
    @items= Item.search(params[:query])
  end

  def typeahead
    render json: Item.where('name ilike ?', "%#{params[:query]}%")
  end

_header.html.erb

<div role="search">
  <%= form_tag items_path, class: 'navbar-form', method: :get do %>
    <div class="form-group">
      <%= text_field_tag :query, params[:query], id: 'typeahead', class: 'search-input form-control',
                                        placeholder: 'Search items' %>
    </div>
    <span class="search-icon">
      <%= button_tag "<i class='fa-navbar fa fa-search'></i>".html_safe, name: nil, class: 'search-button' %>
    </span>
  <% end %>
</div>
.
.
.
<script>
$(document).ready(function(){
    var bloodhound = new Bloodhound({
      datumTokenizer: function (d) {
        return Bloodhound.tokenizers.whitespace(d.value);
        },
      queryTokenizer: Bloodhound.tokenizers.whitespace,
      limit: 10,  
      remote: {url: '/typeahead/%QUERY',
               wildcard: '%QUERY'}  
    });
    bloodhound.initialize();

    $('#typeahead').typeahead(null, {
      name: 'name',
      source: bloodhound.ttAdapter()
    });

    $('#typeahead').bind('typeahead:selected', function(event, datum, name) {
      window.location.href = '/items/' + datum.id;
    });
  });
</script>

config/routes.rb

get 'typeahead/:query', to: 'items#typeahead'
  1. 我的数据源来自我基于用户输入的模型。在我的例子中有预取的地方吗?

  2. 在遥控器中,我将 url 设置为 '/typeahead/%QUERY'。在其他示例中,我看到了类似 '/typeahead?q=%QUERY' 的内容。有什么区别?

  3. bloodhound 中的 prepare 和 wildcard 选项是什么?看了api的解释here还是不明白

正确显示建议下拉菜单的问题是因为我缺少 displayKey: 'name' 作为预输入选项。添加这个解决了我的问题。

$('#typeahead').typeahead(null, {
  name: 'name',
  displayKey: 'name',
  source: bloodhound.ttAdapter()
});