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 3 years have passed since last update.

Rails で検索機能を作ろう(ransack)

Posted at

はじめに

今回はransackというgemを使って検索機能を作っていきます。ransackは少ないコードで複雑な検索機能を簡単に作れるgemでとても便利です。また、ransackではソート機能も簡単に作れるのでそれも含めて作成していきます。

基本的な検索結果の実装

今回検索の対象とするのは、ストレッチ(stretchsテーブル)一覧と、そのカテゴリ(categoriesテーブル)一覧とします。
ストレッチ一覧画面(indexビュー)に検索窓を設けます。

gemをインストール

gem 'ransack';

bundle installでインストール

ビュー

ストレッチのindexビューに検索窓をつける

<div class= serch.id>
      <%= search_form_for @q, class:'form-inline' ,url: stretchs_path do |f| %>
        <%= f.search_field :action_muscles_or_name_cont, class: 'form-control input-lg', placeholder: "ストレッチ名や筋肉名を入力" ,data: {"turbolinks" => false}%>
        <%= f.submit "検索", class: "btn btn-success btn-lg" %>
      <% end %>
</div>

cssで調整

.form-inline .form-control {
    display: inline-block;
    width: 80%;
}

コントローラー

class StretchsController < ApplicationController
  def index
    # 検索機能(検索ワードをparams[:q]で受け取り@stretchsに入れる)
    @q = Stretch.all.ransack(params[:q])
    @stretchs = @q.result(distinct: true).page(params[:page])
  end
end

検索ワードをparams[:q]で受け取り、検索で該当したデータをそれぞれ@stretchsに入れ、
再びindexビューに返す形です。

以上で簡単な検索機能の実装は完了です。

最後に

今回はransackを使って検索機能を作成しました。
間違っていたりするところがあればご教授お願いします。

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?