1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Ransack needs associations explicitly allowlisted as searchable...の対処法

Last updated at Posted at 2023-12-04

self.ransackable_attributesで自身で許可するカラムを、self.ransackable_associationsで関連付けの参照先で許可するmodelを指定できる。
参照先のmodelでは、self.ransackable_attributesで同様にして許可するカラムを指定する。

具体例

PostモデルとTagモデルが多:多で、Postの検索でTagのnameカラムを利用したい場合(tag_postsが中間テーブル)

Post.rb
class Post < ApplicationRecord
  has_many :tag_posts, dependent: :destroy
  has_many :tags, through: :tag_posts

  def self.ransackable_associations(_auth_object = nil)
    #多なので複数形で指定
    ['tags']
  end
end
Tag.rb
class Tag < ApplicationRecord
  has_many :tag_posts, dependent: :destroy

  def self.ransackable_attributes(_auth_object = nil)
    ['name']
  end
end
1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?