ruby-on-rails 错误(找不到profile_image_attachment(:记录在ActiveStorage::Attachment中)的反向关联):

kmbjn2e3  于 11个月前  发布在  Ruby
关注(0)|答案(1)|浏览(90)

在我的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时,我遇到了一个搜索错误。为了解决这个问题,我在模型中使用了defined the 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,但是它不起作用,我已经检查了我所有的模式文件,它正确地生成了active storage of。

rqenqsqc

rqenqsqc1#

你不应该在内置的ActiveStorage::Attachment类中定义或重新定义任何关联。当然你也不应该改变这个类的继承!
查看source,您将看到父类是ActiveStorage::Record
如果你需要允许使用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::Attachment5.26.0版本中的父类是ActiveRecord::Base

相关问题