0
0

[rails]「とりあえずransack付けてみたいだけなんです」

Last updated at Posted at 2024-01-26

自力でプルダウンなど、文字入力以外の検索方法やソート機能を実装しようとすると少し大変かもしれませんが、gemのransackを用いると超簡単に作れてしまいます。

手っ取り早く実装してみたい人向けです。
細かい仕様等は公式ドキュメントを参照してください。

前提

  • crud実装済み
    • 本記事ではpostモデルでMVCを組んでいます

実装

gemのインストール

Gemfile
gem 'ransack' #追記

追記後ターミナルでbundle installを実行

controller記述

PostsController
class PostsController < ApplicationController
    def index
        @posts =  Post.all #投稿一覧表示用(もともとある前提)
        
        @q = Post.ransack(params[:q]) #追記
        @posts= @q.result #追記
    end
end

view記述

index.html.erb
<%= search_form_for @q  do |f| %>
    <%= f.search_field :title_cont %>
    <%= f.submit "search" %></p>
<% end %>

検索フォームでは<%= f.search_field :title_cont %>title_cont部分のように

カラム名_オプションというようなransack特有の記述をします。

※本記事の場合、titleカラムを部分検索できる_contを利用しているという形になります。

この記事では紹介しきれないので詳しくは↓を参考にしてください。

カラム名にオプションを付ければ、セレクトボックスやプルダウン、ラジオボタンで検索を行うことも可能です。

コード自体も一般的な記法にカラム名_オプションとしてするだけなので、是非色々試してみてください。

ソート機能

検索の他にも指定したカラムを昇順⇔降順に並び替えも実装することが可能です。
その際viewの記述は以下のようになります。

index.html.erb
<%= sort_link(@q, :カラム名, "表示したい文字") %>

詳しい仕様は以下記事を参考にしてください。

よくあるエラー

実装して確認しようとすると以下の様なエラーが出るかと思います。

エラー文
Ransack needs HogehogeModel attributes explicitly allowlisted as
searchable. Define a `ransackable_attributes` class method in your `HogehogeModel`
model, watching out for items you DON'T want searchable (for
example, `encrypted_password`, `password_reset_token`, `owner` or
other sensitive information). You can use the following as a base:

class HogehogeModel < ApplicationRecord
  # ...
  def self.ransackable_attributes(auth_object = nil)
    ["created_at", "id", "hogehoge_1", "hogehoge_2", "hogehoge_3", "updated_at"]
  end
  # ...
end

解決策

ご自身のエラー文内にある

エラー文
 def self.ransackable_attributes(auth_object = nil)
   ~~~ご自身のカラムの情報~~~
 end

の部分を実装しているモデルに張り付けることにより解消されます。
※本記事の場合Postモデルに張り付ける。

また、アソシエーションを行っている場合再度似たようなエラー文が出ます。

エラー文
 def self.ransackable_associations(auth_object = nil)
    ~~~省略~~~
 end

先程と似ていますが前回ransackable_attributesだったのに対し、今回はransackable_associationsと表記されています。
こちらも同じくモデルに張り付けることでエラーが解消します。

参考

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