Rails 7 + Active Admin下Ransack需AdminUser属性显式白名单错误
解决ActiveAdmin中Ransack要求显式定义可搜索属性的RuntimeError
错误详情
在访问Admin::AdminUsers#index页面时触发RuntimeError,错误触发路径:/home/vidur/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/activeadmin-3.2.0/app/views/active_admin/resource/index.html.arb第3行。
错误原因:Ransack要求AdminUser模型必须显式声明可被搜索的属性白名单,且需排除敏感字段(如encrypted_password、password_reset_token等)。
解决方案
在AdminUser模型中添加ransackable_attributes类方法,仅将安全、可公开搜索的属性加入白名单:
class AdminUser < ApplicationRecord # 其他已有代码... def self.ransackable_attributes(auth_object = nil) ["created_at", "email", "id", "remember_created_at", "updated_at"] end # 其他已有代码... end
补充说明
- 上述代码移除了
encrypted_password、reset_password_token、reset_password_sent_at等敏感字段,避免这些信息被用于搜索 - 如果需要支持关联模型的搜索,还可以在模型中添加
ransackable_associations方法,返回允许搜索的关联名称数组(例如["roles"])
内容的提问来源于stack exchange,提问作者vidur punj
相关产品推荐
相关产品推荐

