扩展ActiveStorage ::附件 – 添加自定义字段

我想扩展ActiveStorage :: Attachment类,并为附件的可见性添加一个枚举属性。

我最初的方法是在\ app \ models目录中创建一个新文件attachment.rb,如下所示。

class ActiveStorage::Attachment < ActiveRecord::Base enum visibility: [ :privately_visible, :publicly_visible] end 

这不起作用。

欢迎任何建议。 什么是Rails扩展类的方法?

更新

我有一个解决方案现在部分工作。 为此,我创建了一个扩展名active_storage_attachment_extension.rb并将其放在\ lib中

 module ActiveStorageAttachmentExtension extend ActiveSupport::Concern included do enum visibility: [ :privately_visible, :publicly_visible] def describe_me puts "I am part of the extension" end end end 

扩展在extensions.rb初始化期间加载

 ActiveStorage::Attachment.send(:include, ::ActiveStorageAttachmentExtension) 

不幸的是,它只是部分工作:虽然枚举方法是公开可见的? 和privately_visible? 在视图中可用,它们在控制器中不可用。 当调用控制器中的任何方法时,枚举似乎已经消失。 我收到“NoMethodError – undefined method”错误。 令人惊讶的是,一旦enum方法在控制器中被调用一次,它们在视图中也不再可用。 我假设ActiveStorage :: Attachment类被动态重新加载,并且扩展会丢失,因为它们仅在初始化期间添加。

有任何想法吗?

正如我的评论中所提到的,它需要带有以下内容的文件app/models/active_storage_attachment.rb

 class ActiveStorageAttachment < ApplicationRecord enum visibility: [ :privately_visible, :publicly_visible] end 

然后,您还需要将类型integer的列可见性添加到表active_storage_attachments

 class AddVisibilityToActiveStorageAttachments < ActiveRecord::Migration[5.2] def change add_column :active_storage_attachments, :visibility, :integer end end 

访问ActiveStorageAttachment的新列

我使用我的模型做了一个例子:我有一个用户has_one_attached:avatar。

我可以通过user.avatar.attachment.inspect访问active_storage_attachments表,该表返回例如#

请注意,列visibility的值是纯整数,不是由visibility数组转换的(我仍然想知道为什么)。

一种可能的解决方法是在User模型中定义类似avatar_attachment的方法,如下avatar_attachment

 class User < ApplicationRecord has_one_attached :avatar def avatar_attachment ActiveStorageAttachment.find_by(name: 'avatar', record_type: 'User', record_id: self.id) end end 

现在user.avatar_attachment.inspect返回#

现在,所有与可见性数组相关的方法都可用。 记录更新也有效:

 user.avatar_attachment.publicly_visible! # => true 

我假设ActiveStorage :: Attachment类被动态重新加载,并且扩展会丢失,因为它们仅在初始化期间添加。

你是对的。 使用Rails.configuration.to_prepare在应用程序启动后和每次重新加载代码时混合模块:

 Rails.configuration.to_prepare do ActiveStorage::Attachment.send :include, ::ActiveStorageAttachmentExtension end