そういうことだったんですね

いろいろ調べたり学んだりしたことを忘れないように書き連ねています

Rails - sunspot で全文検索をする(2)

Rails - sunspot で全文検索をする(1) - そういうことだったんですね の続きです。

each_hit_with_result を使う

ブロック引数として hit, result の2つ渡されます。

result は検索対象モデルのオブジェクトが返るため属性にアクセスできます。

@search.each_hit_with_result do |hit,result|
  puts hit.primary_key    # 主キーにアクセス
  puts result.title       # 属性にアクセス
  puts result.created_at  # 作成日にアクセス
end

 

検索画面を作成する

コントローラの生成

今回は post_search というコントローラ名とし index と search というアクションを追加します

$ rails generate controller post_search index search

ビューの編集

はじめに表紙。検索ワードを入力するフォームを作成します

app/views/post_controller/index.html.erb

対応するモデルを作成しなかったので form_tag を使います。

<%= form_tag '/post_search/search', method: "get" do %>
  <%= text_field_tag :q %>
  <%= submit_tag '検索' %>
<% end %>

GETでアクセスし、検索ワードのパラメータはqとします。

app/views/post_controller/search.html.erb

結果出力をする画面を作成します。

  • ヒット件数(@search.totalを表示
  • タイトルを表示(hit.primary_key
  • スニペットを表示する(highlight.format)
  • スニペットの一部を *キーワード* のように強調表示する
<p>
検索ワード: <%= params[:q] %>
</p>
<p>
<%= @search.total %> 件ヒット
</p>
<ul>
<% @search.each_hit_with_result do |hit, result| %>
    <li><div>Post #{<%= hit.primary_key %>}</div>
    <div><%= result.title %></div>
    <% hit.highlights(:body).each do |highlight| %>
        <%= highlight.format  { |word| "*#{word}*" } %>
    <% end %>
    </li>
<% end %>
</ul>

コントローラの編集

search アクションの編集を行います。

def search
  @search = Post.search do
      fulltext params[:q] do
        highlight :body
      end
  end 
end

Postのクラスメソッドsearch を呼び出します。highlight は強調表示のものです

結果画面

f:id:babiy3104:20130828162523p:plain

Railsレシピブック 183の技

Railsレシピブック 183の技