0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Rails】ransack版検索フォーム

Last updated at Posted at 2021-06-24

概要

ransackというgemを用いて、railsアプリケーション内にユーザー検索機能を実装する

##実装手順

Gemfile

gem 'ransack'

記述後にbundle install

####users_controller

def index
    @q = User.ransack(params[:q])
    @user = @q.result(distinct: true).includes(:user).order(created_at: :desc)
  end

・User.ransack(params[:q] で検索データを取得
・distinct: true を用いることで、重複したデータをまとめる

users/index.html.erb

<%= render 'search_form', q: @q, url: users_path' %>

パーシャルに切り分けることによって、再利用性の向上に繋がる

users/_search_form.html.erb

<%= search_form_for q, url: url do |f| %>
  <div class="input-group mb-3">
    <%= f.search_field :title_or_body_cont, class: 'form-control', placeholder: t('defaults.search_word') %>
    <div class="input-group-append">
      <%= f.submit class: 'btn btn-primary' %>
    </div>
  </div>
<% end %>

・title_or_body_cont により、titleとbodyのどちらかのカラムに含まれているかどうかを判定する検
 索フォームになっている

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?