iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🌟

How to fix the "Ransack needs attributes explicitly allowlisted..." error

に公開

How to deal with the error: Ransack needs attributes explicitly allowlisted as searchable

There was a breaking change in Ransack v4.0.0.

[SECURITY] Require explict allowlisting of attributes and associations

Previously, searching and sorting were possible without explicit permission, but starting from version 4.0.0, if you do not create an allowlist, the following error will occur:

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

As the error message states, you need to define a ransackable_attributes method in the model you want to filter/search, and list the columns you want to permit.

For more details, it is recommended to check the documentation on Authorization (allowlisting/denylisting).

When you want to search parent or child models

If you try to search parent or child models, the following error will occur:

Ransack needs HogehogeModel associations explicitly allowlisted as
searchable. Define a `ransackable_associations` 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_associations(auth_object = nil)
    ["child_hogehoges", "hogehoge"]
  end
  # ...
end

Similarly, this was resolved by listing the permitted models in the ransackable_associations method.

It took me a long time because I was trying to fix it without looking at the error message or the documentation, but I really need to read them properly...

Discussion