Rails使用自动完成function实现搜索

我不确定如何为我的搜索function提供自动填充表单。

 "get" do %>   nil %>  

我有一个以下的控制器,它有一个自定义的动作

  def query @users= Search.user(params[:query]) @article= Search.article(params[:query]) end 

该模型如下:

 def self.user(search) if search User.find(:all, :conditions => ['first_name LIKE ?', "%#{search}%"]) else User.find(:all) end end def self.article(search) if search Article.find(:all, :conditions => ['title LIKE ?', "%#{search}%"]) else Article.find(:all) end end 

现在这项工作非常适合搜索但是,我希望它能告诉我结果我正在编写它,并且我不能使用jquery自动完成,因为它是两个对象。

使用Twitter typeahead 。 这里有一些例子:

http://twitter.github.com/typeahead.js/examples/

Twitter预先输入以及您需要的所有信息可从https://github.com/twitter/typeahead.js/获得

如何使用

使用取决于您将具有“建议”的数据。 例如,如果它是静态数据(总是相同),您可以这样实现:

 $('input.typeahead').typeahead({ local: ['suggestion1', 'suggestion2', 'suggestion3',...., 'suggestionN'] #The typeahead is going to load suggestions from data in local. }); 

如果数据发生变化并且来自模型或数据库表,那么您可以尝试:

 Controller: def load_suggestions @suggestions = MyModel.select(:name) or MyModel.find(:all, conditions: [...]) #Select the data you want to load on the typeahead. render json: @suggestions end JS file: $('input.typeahead').typeahead([ { prefetch: 'https://www.mipage.com/suggestion.json' #route to the method 'load_suggestions' #This way, typeahead will prefecth the data from the remote url } ]);