Active Storage关联报错:反向关联找不到及未知关键字问题
解决Active Storage与Active Admin结合的两个关联报错
问题分析与修复方案
涉及报错
Could not find the inverse association for profile_image_attachment (:record in ActiveStorage::Attachment)- 访问用户详情页时出现
unknown keywords: :class_name, :as, :inverse_of
根本原因
你手动重写了ActiveStorage::Attachment模型(app/models/active_storage/attachment.rb),覆盖了Active Storage原生的关联定义,同时代码存在语法错误(class_name: "ActiveStorage::Blob未闭合引号),导致原有多态关联和Blob关联被破坏,引发关联查找失败和参数识别错误。
修复步骤
删除自定义的
app/models/active_storage/attachment.rb文件
Active Storage已经内置了ActiveStorage::Attachment的完整定义,手动重写会直接破坏原生关联逻辑,这是所有报错的根源。通过类扩展添加Ransack支持(替代重写模型)
若要让ActiveStorage::Attachment支持Active Admin的搜索功能,不要重写整个类,而是用class_eval扩展:
创建config/initializers/active_storage_ransack.rb文件,写入以下代码:ActiveStorage::Attachment.class_eval do def self.ransackable_attributes(auth_object = nil) ["blob_id", "created_at", "id", "name", "record_id", "record_type"] end end保留User模型的正确关联写法
确保app/models/user.rb中的关联定义保持简洁,无需额外添加inverse_of:class User < ApplicationRecord has_one_attached :profile_image # 其他模型代码... end重启服务器验证
重启Rails服务器后,访问用户详情页和Active Admin后台,两个报错应会消失。
内容的提问来源于stack exchange,提问作者Rohit Verma
相关产品推荐
相关产品推荐

