LoginSignup
0
0

More than 1 year has passed since last update.

ransackで検索機能を追加する

Posted at

Ransackのインストール

gem 'ransack'

‘bundle install’でインストール完了

コントローラーに検索機能を追加する

コントローラー内のindexアクションなどに後に記述するviewの検索フォームからリクエストされたパラメータを使った検索機能を作っておく。

# 例)ユーザーの名前で検索をかける
def index
  @q = User.ransack(params[:q]) # この部分で検索が行われる
  @users = @q.result
end

view側に検索フォームを追加する

view側には、ransackが提供するsaerch_form_forというヘルパーを使って検索フォームを追加する。

= search_form_for @q, class: 'md-5' do |f|
  .form-group.row
    = f.label :name_cont, '名前', class: 'col-sm-2 col-form-label'
    .col-sm-10
      = f.search_field :name_cont, class: 'form-control'     
  .form-group 
     = f.submit class: 'btn btn-outline-primary'

この時、検索フィールドの名前を一定のルールで命名する必要がある。

今回は「名前に〇〇を含む」としたいのでname_contとする。_contはransackが提供する検索マッチャー。

全検索マッチャー

https://github.com/activerecord-hackery/ransack/blob/master/lib/ransack/locale/en.yml#L15

0
0
0

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
0
0