LoginSignup
1
3

More than 3 years have passed since last update.

【Rails】ransackで検索機能を実装

Last updated at Posted at 2020-03-10

ransackというgemを使って、検索、ソートの機能を実装したのでまとめます。
手軽にできて良い感じでした。

基本的な使い方

Gemfile
gem 'ransack'
terminal
$ bundle install
users_controller.rb
def index
  @q = User.ransack(params[:q])
  @users = @q.result(distinct: true)
end
index.html.erb
<!-- 検索フォーム -->
<%= search_form_for @q do |f| %>
  <%= f.label :name, "名前" %>
  <%= f.search_field :name_cont %>
  <%= f.label :email, "メールアドレス" %>
  <%= f.search_field :email_cont %>
  <%= f.submit "検索" %>
<% end %>

<!-- ユーザー一覧 -->
<table>
  <tr>
    <th>名前</th>
    <th>メールアドレス</th>
  </tr>
  <% users.each do |user| %>
  <tr>
    <td><%= user.name %></td>
    <td><%= user.email %></td>
  </tr>
  <% end %>
</table>

ソート機能

index.html.erb
<!-- ユーザー一覧 -->
<table>
  <tr>
    <th><%= sort_link(@q, :name, "名前") %></th>
    <th><%= sort_link(@q, :email, "メールアドレス") %></th>
  </tr>
.
.

検索条件を組み合わせる

ステータスがアクティブなユーザーの中から検索して、ページネーションをつける

users_controller.rb
def index
  @q = User.ransack(params[:q])
  #後ろに自由に条件を追加できる
  @users = @q.result(distinct: true).where(status: 1).page(params[:page])
end

様々な検索方法

検索フォームの中で:name_contなどと記載していた部分は、他にもいろんな指定ができます。

検索方法 意味(英語) 意味
*_eq equal 等しい
*_not_eq not equal 等しくない
*_lt less than より小さい
*_lteq less than or equal より小さい(等しいものも含む)
*_gt grater than より大きい
*_gteq grater than or equal より大きい(等しいものも含む)
*_cont contains value 部分一致(内容を含む)

その他:activerecord-hackery/ransack: Object-based searching.

参考

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