ruby-on-rails - 自动完成搜索的 Rails 实现

标签 ruby-on-rails ruby ruby-on-rails-3 autocomplete

我不确定如何为我的搜索功能添加自动完成表单。

<%= form_tag "/search", :method => "get" do %>
    <%= text_field_tag :query, params[:query] %>
    <%= image_submit_tag "site/blankimg.png", :name => nil %>
<% end %>

我有一个具有自定义操作的 Controller

   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
   }
]);

关于ruby-on-rails - 自动完成搜索的 Rails 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15191240/

相关文章:

mysql - Rails 4 : Error when trying to sort by using arel_table. maximum.desc

ruby - 使用 Range 与 Times 在 Ruby 中循环差异

ruby - 事件记录范围 : Strange behaviour with select on relation

ruby-on-rails - Ruby on Rails ActiveRecord 约定

ruby-on-rails - 如何删除嵌套在不同范围内的重复路由?

ruby-on-rails - 如何定义链接路径

ruby-on-rails - 使用 RackDAV 在 Rails 应用程序中公开 webdav 目录,我如何映射该目录以提供服务?

ruby-on-rails - Rails 中 1 个模型的 2 个用户定义类

ruby-on-rails - Rails 3 使用 Ajax 计算行总数

ruby-on-rails - 在devise 2.0上跳过omniauth-twitter的电子邮件验证