Rails 4搜索功能

时间:2014-12-25 08:43:26

标签: ruby-on-rails search ruby-on-rails-4 activerecord

我有这个简单的搜索功能:

class SearchController < ApplicationController
 def index
    if params[:search].blank?
      redirect_to root_path
    else
      @results = Post.search(params[:search])
    end
  end
end

我想实现以下功能,但我很难编写代码:

1.如何记录每个输入搜索词,并查看哪些搜索词是搜索次数最多的词。我想过使用&#34; first_or_create&#34;方法...

2.给我这个标题:&#34;彼得保罗玛丽&#34;,如何拆分它们并链接到每个术语以搜索搜索功能

请告知。

1 个答案:

答案 0 :(得分:1)

1.我认为您可以使用包含每个单词的查询结果的二维数组。

@maching_posts = Array.new
@terms = params[:search].split

@terms.each do |term|
  result = Post.where(title: term)
  @maching_post << result
end

现在,你有阵列&#39; @ maching_post&#39;包含每个单个术语的查询结果。行[0]包含第一项等的结果。

您可以使用此数组生成视图。像这样:

<% @terms.each_with_index do |term, index| %>
  <span>Results of <%= term %></span>
  <% @maching_post[index].each do |post| %>
    <%= post.title %></br>
  <% end %>
<% end %>

2.要从字符串中获取单个单词,您可以使用split()方法。

       "Peter Paul Mary".split 

此方法返回数组[&#34; Peter&#34;,&#34; Paul&#34;,&#34; Mary&#34;] 要链接每个术语,请使用

link_to 'term', controller: :search, action: :index, search: 'term'

你应该在循环中使用这个方法,比如

<% "Peter Paul Mary".split.each do |term| %>
  <%= link_to term, controller: :search, action: :index, search: term %>
<% end %>