【问题标题】:Rails implementation of search with autocompleteRails 实现自动完成搜索
【发布时间】:2013-02-17 22:22:12
【问题描述】:

我不确定如何为我的搜索功能设置自动填充表单。

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

我有一个具有自定义操作的以下控制器

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

【问题讨论】:

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


    【解决方案1】:

    使用 Twitter 预输入。这里有一些例子:

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

    Twitter typeahead 和你需要的所有信息都可以从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
       }
    ]);
    

    【讨论】:

    • 如何将我的模型与它挂钩?
    • 谢谢,我正在阅读他们的 API,第一次看到有点混乱
    • 你必须同时下载 typeahead.js 和 typeahead.css 文件
    • 你能确认 Rails 4 的 gem 吗?是bootstrap-typeahead-rails吗?那么在视图中拥有简单的&lt;input class="typeahead"... 并启用 gem 资产就足够了?如果我输入 sugg 我应该能够看到所有选项:suggestion1suggestion2 等?
    猜你喜欢
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多