Javascript 正在工作的示例?

Javascript 正在工作的示例?,javascript,ruby-on-rails,ruby,ruby-on-rails-4,twitter-typeahead,Javascript,Ruby On Rails,Ruby,Ruby On Rails 4,Twitter Typeahead,我正在尝试在我的应用程序中安装twitter-typeahead-railsgem。我遵循了几个不同的教程,但都会导致错误 有人有这个gem的工作示例吗?在gem文件中指定gem作为依赖项: # Gemfile gem 'bootstrap-multiselect-rails' 需要在清单中预先输入文件: // app/assets/javascripts/application.js //= require twitter/typeahead //= require twitter/ty

我正在尝试在我的应用程序中安装
twitter-typeahead-rails
gem。我遵循了几个不同的教程,但都会导致错误


有人有这个gem的工作示例吗?

gem文件中指定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/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
GET request to/typeahead/%QUERY以以下形式返回json:

[
  {
    "name": "foo",
    "id": "1"
  },
  {
     "name": "bar",
     "id": "2"
  }
]

公认的答案并不完全正确

似乎有两种不同的宝石在做大致相同的事情:

bootstrap multiselect rails
目前在gem存储库中的版本0.9.9上,并且具有与文章中提到的不同的资产需求结构。该创业板的资产需要包括:

In application.js:
//= require bootstrap-multiselect

In application.css:
*= require bootstrap-multiselect
有关Git的更多信息:

或者,还有TwitterTypeahead rails
gem,当前版本为0.11.1,它似乎需要使用,并包含在接受答案的其余部分中

有关Git的更多信息:

这两个gems似乎都是在5-6个月前写这篇文章时更新的

最后,在猎犬JS中指定的远程URL不正确:

remote: '/typeahead/%QUERY'
需要

remote: {url: '/typeahead/%QUERY', wildcard: '%QUERY'}

希望这对某人有所帮助

这是javascript,所以请将其放入与您的控制器对应的javascript文件或任何适合您的应用程序的文件中。确保它在DOM就绪后运行。如果您使用的是turbolinks(rails4+):
$(document).on('page:change',function(){//DOM在这里就绪})。您的视图中有什么?视图中只需要一个文本输入。我更新了我的答案以确保完整性。等等,那么我如何将其链接到实际数据以进行搜索?这是一个很好的答案。有一件事情可能并不明显:控制器中的
typeahead
方法需要处理某种通配符/子字符串搜索。按原样,您可能会得到一个空结果。我怀疑这就是@rnjai遇到的问题。
remote: '/typeahead/%QUERY'
remote: {url: '/typeahead/%QUERY', wildcard: '%QUERY'}