【发布时间】: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'
我的数据来源来自我基于用户输入的模型。在我的示例中有预取的地方吗?
在遥控器中,我将 url 设置为
'/typeahead/%QUERY'。在其他示例中,我看到了类似'/typeahead?q=%QUERY'的内容。有什么区别?Bloodhound 中的准备和通配符选项是什么?看过api解释here还是不明白。
【问题讨论】:
-
你重启你的rails服务器了吗?
-
@duhaime 是的,我的问题是我错过了预输入下的
display选项 -
啊,很好!如果您找到了解决方案,如果您在下面输入它可能会对未来的访问者有所帮助:)
标签: ruby-on-rails ruby-on-rails-4 search autocomplete typeahead.js