14
6

More than 1 year has passed since last update.

ransackで"Ransack needs attributes explicitly allowlisted..."のエラー解消法

Posted at

概要

ransackの4.0.0のアップデートでBreaking Changesがあり、そのうちの1つに

  • [SECURITY] Require explict allowlisting of attributes and associations
    が含まれています
    このアップデートの影響で関係するモデルにホワイトリストを登録しなければいけなくなりました。

エラーログ

ransackを使用しているページにアクセスすると以下のエラーが表示されてしまいました。。。。

ActionView::Template::Error (Ransack needs HogeModel attributes explicitly allowlisted as
    | searchable. Define a `ransackable_attributes` class method in your `HogeModel`
    | 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:
    | 
    | ```ruby
    | class HogeModel < ApplicationRecord
    | 
    |   # ...
    | 
    |   def self.ransackable_attributes(auth_object = nil)
    |     ["id", "hogehoge_1", "hogehoge_2", "hogehoge_3", "updated_at"]
    |   end
    | 
    |   # ...

解消法

エラーログにも書かれていますが、ransackで検索対象にしているモデル内にホワイトリストを登録するメソッドを作成し、検索に使用するカラムを記述する必要があります。

例えばメールアドレス検索と名前検索を使用している場合は

HogeModel
def self.ransackable_attributes(auth_object = nil)
    ["email", "name"]
end

と書く必要があります。

子モデルで検索している場合どうするか

hogeとfugaが1対1のアソシエーションが組まれていて(fugaが子とする)、hogeの検索にfuga内のカラムが必要な場合
例えば電話番号検索機能があり、電話番号はhogeではなくfugaカラムにある場合は以下のように記述します

HogeModel
def self.ransackable_associations(auth_object = nil)
    ["fuga"] #アソシエーション先を記述
end
FugaModel
def self.ransackable_attributes(auth_object = nil)
    ["phone_number"]
end

以上です!

参考

公式ドキュメント
リリースノート

14
6
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
14
6