提问人:Rohit Verma 提问时间:10/27/2023 最后编辑:mechnicovRohit Verma 更新时间:10/30/2023 访问量:32
错误(找不到 profile_image_attachment (:record in ActiveStorage::Attachment) 的反向关联):
Error (Could not find the inverse association for profile_image_attachment (:record in ActiveStorage::Attachment)):
问:
在我的文件中,我使用了这段代码app/models/active_storage/attachment.rb
class ActiveStorage::Attachment < ApplicationRecord
belongs_to :blob, class_name: "ActiveStorage::Blob
def self.ransackable_attributes(auth_object = nil)
["blob_id", "created_at", "id", "name", "record_id", "record_type"]
end
end
使用 Active Storage 创建 Active Admin 时,我遇到了搜索错误。为了解决这个问题,我在模型中使用了定义可掠夺的方法。在我的用过app/models/user.rb
has_one_attached :profile_image
当我打开此链接时 http://127.0.0.1:3000/users/1 它显示此错误:
unknown keywords: :class_name, :as, :inverse_of
当我打开这个链接时,http://127.0.0.1:3000/admin 它成功打开
我在我的文件中使用了 inverse of,但它不起作用,我已经检查了我所有的模式文件,它正确地生成了 activestorage。app/models/user.rb
答:
不应在内置类中定义或重新定义任何关联。当然,你不应该改变这个类的继承!ActiveStorage::Attachment
查看源代码,您将看到父类是 .并且有选择权ActiveStorage::Record
belongs_to :blob
autosave
如果您需要允许使用 ransack 进行搜索,只需使用 ransack 方法重新打开此类即可。只定义 ransack 方法,不更改其他内容
可以使用初始值设定项来修补内置类
# config/initializers/active_storage.rb
ActiveSupport.on_load(:active_storage_attachment) do
class ActiveStorage::Attachment < ActiveStorage::Record
def self.ransackable_attributes(auth_object = nil)
%w[blob_id created_at id name record_id record_type]
end
end
end
请注意这里的钩子,它来自上面的源代码。这是一个重要的时刻,因为只有当所需的类已经加载时,你才能成功修补on_load
另请注意,继承在较旧的 rails 中是不同的:在 5.2 和 6.0 版本中,ActiveStorage::Attachment 的父类是 ActiveRecord
::Base
。而且 5.2 不支持钩子
评论