【问题标题】:Getting typeahead to work with rails search提前输入以使用 Rails 搜索
【发布时间】:2016-04-15 00:29:20
【问题描述】:

我在我的 rails 4 应用程序中使用 typeahead v0.10.5 进行了 typeahead 和 search,但自从更新到 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 中的准备和通配符选项是什么?看过api解释here还是不明白。

【问题讨论】:

  • 你重启你的rails服务器了吗?
  • @duhaime 是的,我的问题是我错过了预输入下的 display 选项
  • 啊,很好!如果您找到了解决方案,如果您在下面输入它可能会对未来的访问者有所帮助:)

标签: ruby-on-rails ruby-on-rails-4 search autocomplete typeahead.js


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2016-12-21
    • 2015-01-04
    • 2018-06-19
    • 2012-08-01
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多