工作的twitter-typeahead例子?
我正在尝试将twitter-typeahead-rails
gem安装到我的应用程序中。 我已经按照几个不同的教程,但所有教程都会导致错误。
有没有人有这个gem的工作示例?
在Gemfile
gem指定为依赖Gemfile
:
# 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 -->
路线:
# 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请求以下列forms返回json:
[ { "name": "foo", "id": "1" }, { "name": "bar", "id": "2" } ]
接受的答案并不完全正确。
似乎有两种不同的gem大致相同:
bootstrap-multiselect-rails
目前在gem存储库中的版本为0.9.9,并且具有不同的资产需求结构,如post中所述。 这个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'}
希望这有助于某人