错误(无法找到 profile_image_attachment 的反向关联(:在 ActiveStorage::Attachment 中记录)):

问题描述 投票:0回答:1

在我的

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 时,我遇到搜索错误。为了解决这个问题,我在模型中定义了 ransackable 方法。在我的

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它打开成功

enter image description here

我在我的

app/models/user.rb
文件中使用了 inverse of ,但它不起作用我已经浏览了所有模式文件,它正确生成了 activestorage 。

ruby-on-rails rails-activerecord rails-activestorage
1个回答
0
投票

您不应在内置

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 中的继承有所不同:

ActiveStorage::Attachment
5.26.0 版本中的父类是
ActiveRecord::Base
。而且5.2不支持hooks

© www.soinside.com 2019 - 2024. All rights reserved.