【发布时间】:2015-03-22 00:49:12
【问题描述】:
我正在尝试将twitter-typeahead-rails gem 安装到我的应用程序中。我遵循了几个不同的教程,但都导致错误。
有人有这个 gem 的工作示例吗?
【问题讨论】:
标签: javascript ruby-on-rails ruby ruby-on-rails-4 twitter-typeahead
我正在尝试将twitter-typeahead-rails gem 安装到我的应用程序中。我遵循了几个不同的教程,但都导致错误。
有人有这个 gem 的工作示例吗?
【问题讨论】:
标签: javascript ruby-on-rails ruby ruby-on-rails-4 twitter-typeahead
在 Gemfile 中指定 gem 作为依赖项:
# Gemfile
gem 'bootstrap-multiselect-rails'
在清单中需要预先输入文件:
// app/assets/javascripts/application.js
//= require twitter/typeahead
//= require twitter/typeahead/bloodhound
Javascript:
// app/assets/javascripts/models_controller.js
// initialize bloodhound engine
var bloodhound = new Bloodhound({
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
// sends ajax request to /typeahead/%QUERY
// where %QUERY is user input
remote: '/typeahead/%QUERY',
limit: 50
});
bloodhound.initialize();
// initialize typeahead widget and hook it up to bloodhound engine
// #typeahead is just a text input
$('#typeahead').typeahead(null, {
displayKey: 'name',
source: bloodhound.ttAdapter()
});
// this is the event that is fired when a user clicks on a suggestion
$('#typeahead').bind('typeahead:selected', function(event, datum, name) {
doSomething(datum.id);
});
查看:
<-- app/views/models/whatever.html.erb -->
<input type="text" id="typeahead">
路线:
# config/routes.rb
get 'typeahead/:query' => 'models#typeahead'
控制器:
# app/controllers/models_controller.rb
def typeahead
render json: Model.where(name: params[:query])
end
## note: the above will only return exact matches.
## depending on the database being used,
## something else may be more appropriate.
## here is an example for postgres
## for case-insensitive partial matches:
def typeahead
render json: Model.where('name ilike ?', "%#{params[:query]}%")
end
对/typeahead/%QUERY的GET请求返回json格式为:
[
{
"name": "foo",
"id": "1"
},
{
"name": "bar",
"id": "2"
}
]
【讨论】:
$(document).on('page:change', function() { // DOM is ready in here });.
typeahead 方法需要处理某种通配符/子字符串搜索。照原样,您可能会得到一个空的结果。我怀疑这是@rnjai 遇到的问题。
接受的答案并不完全正确。
似乎有 2 个不同的 gem 在做大致相同的事情:
bootstrap-multiselect-rails 目前在 gem 存储库中的版本为 0.9.9,并且具有不同的资产需求结构,如帖子中所述。此 gem 的资产需要包含为:
In application.js:
//= require bootstrap-multiselect
In application.css:
*= require bootstrap-multiselect
更多关于 Git:https://github.com/benjamincanac/bootstrap-multiselect-rails
或者,有 twitter-typeahead-rails gem,目前版本为 0.11.1,似乎需要使用和包含,如接受答案的其余部分所述。
更多关于 Git:https://github.com/yourabi/twitter-typeahead-rails
在撰写本文时,这两个 gem 的最后一次更新似乎是大约 5-6 个月前。
最后,Bloodhound JS 中指定的远程 URL 不正确:
remote: '/typeahead/%QUERY'
需要
remote: {url: '/typeahead/%QUERY', wildcard: '%QUERY'}
希望这对某人有所帮助
【讨论】: