LoginSignup
87
96

More than 3 years have passed since last update.

ransackでRailsアプリのヘッダーに検索機能をつける

Last updated at Posted at 2016-03-06

ヘッダーに検索ボックス(機能)つけたい!!!
イメージ↓↓↓↓↓
スクリーンショット 2016-08-13 20.59.28.png

application.html.erbにヘッダーの記述があるサンプルです。

ransackのGithub
https://github.com/activerecord-hackery/ransack

Gemfile

gem 'ransack'

追加してbundle install

コントローラ

application_controller.rb
before_action :set_search

def set_search
  #@search = Article.search(params[:q])
  @search = Article.ransack(params[:q]) #ransackメソッド推奨
  @search_articles = @search.result.page(params[:page])
end

application_controllerということに注意
仮にarticles_controllerに書くとarticles_controllerを使わないページを表示した時にエラーになる。
kaminariでページネーションをつけているのでpage(params[:page])をつけた。
searchメソッドよりransackメソッド推奨なのでransackメソッドを使った。(下のコメント参照)

ビュー(検索ボックス側)

application.html.erb
<dl class="searchbox">
  <%= search_form_for @search, url: articles_path do |f| %>
    <dt><%= f.text_field :title_cont ,placeholder: '検索するテキストを入力...' %></dt>
    <dd><%= f.submit ("検索") , class: 'search-btn'%></dd>
  <% end %>
</dl>

url:でリダイレクト先を指定した。
:???_contで検索したいカラムを指定できる。

デザインのサンプル

application.css
/* 検索ボックス */
dl.searchbox{
  width: 350px;
  position:relative;
  background-color:#fff;
  border:1px solid #aaa;
  border-radius:6px;
}
dl.searchbox dt{
  padding:3px;
}
dl.searchbox dt input{
  width:70%;
  height:30px;
  line-height:30px;
  background:none;
  border:none;
}
dl.searchbox dd{
  position:absolute;
  top:1px;
  right:1px;
  width:30%;
}
.search-btn{
  display:block;
  background:#5fad35;
  width:100%;
  height:36px;
  line-height:36px;
  border:none;
  border-radius: 0 6px 6px 0;
  color:#FFF;
}

.search-btn:hover {
  background:#228B22;
}

ビュー(表示側)

search_form_forで指定した(articles_path)リダイレクト先
今まではarticles_controllerで

def index
  @articles = Article.all
  〜略〜
end

<% @articles.each do |article| %>
〜略〜
<% end %>

で記事一覧を表示させていた。
検索した場合はapplication_controller.rbで@search_articlesに検索された結果が返ってくるので

<% @search_articles.each do |article| %>
  〜略〜
<% end %>

に書き換える。
検索してない場合は全てのデータが返ってくる。

まとめ

参考サイト

RubyDoc.info
http://www.rubydoc.info/gems/ransack/1.7.0#Ransack__search_method

87
96
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
87
96