自动完成搜索的 Rails 实现 [英] Rails implementation of search with autocomplete

查看:20
本文介绍了自动完成搜索的 Rails 实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am not to sure how to have an autocomplete form to my search function.

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

我有以下控制器,它具有自定义操作

I have a controller of the following which has a customized action

   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 自动完成功能,因为它是两个对象.

Now this work great for a search but it, i would like it to show me the result has i am writing it, and i can't use jquery autocomplete because it is two object.

推荐答案

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

Use Twitter typeahead. There are some examples here:

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

Twitter typeahead 和您需要的所有信息都可以从 https://github.com/twitter/typeahead.js/

Twitter typeahead and all the information you need is available from https://github.com/twitter/typeahead.js/

如何使用

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

The use depends on the data you are going to have as 'suggested'. For example, if it is static data (always going to be the same) you can implement it this way:

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

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

If the data changes and it came from a model or a db table then you can try:

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

这篇关于自动完成搜索的 Rails 实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆