所以我决定在ActiveStorage :: Attachment对象中添加一个url
attr_accessor。
在开发过程中,补丁会持续一段时间,直到它“似乎已经丢失”。意味着它可以工作几分钟,然后它不再起作用了。然后我需要重新启动服务器才能再次应用补丁。我相信我没有正确修补,我需要在那个问题上提出建议。
这是我尝试过的:
LIB / EXT / active_storage / attachment.rb
第一次尝试 :
module ActiveStorageUrl
extend ActiveSupport::Concern
included do
attr_accessor :url
end
end
ActiveStorage::Attachment.send :include, ActiveStorageUrl
第二次尝试
class ActiveStorage::Attachment < ActiveRecord::Base
attr_accessor :url
end
顺便说一句,在这两种情况下它都加载了这个:
配置/初始化/ monkey_patches.rb
require 'ext/active_storage/attachment'
因此,当它工作时,我没有错误消息,但过了一段时间补丁“disapear”(缺乏更好的条款),我得到以下错误,告诉我我的attr_accessor不再存在。 Rails必须重新加载ActiveStorage类,我的补丁丢失了。
Module::DelegationError in Products#images
url delegated to blob, but blob is nil
您可能正在丢失您的猴子补丁,因为代码被重新加载并且您的ext / active_storage / attachment不再需要。
您可以告诉Rails在启动时运行回调,并且每次都像这样重新加载代码。
Rails.configuration.to_prepare do
require 'ext/active_storage/attachment'
end
我将ActiveStorage::Attachment
MonkeyPatch放在/ app / models / active_storage /中
如果附件已更改,我已添加回调以获取通知。它一直很好用。
也许这就是问题所在。
似乎与delegate_missing_to
有关,例如
delegate_missing_to :blob
https://github.com/rails/rails/blob/master/activestorage/app/models/active_storage/attachment.rb#L14
无论如何,它可能与attr_accessor
如何工作有关,我会尝试:
def url
@url
end
def url=(url)
@url = url
end
而不是attr_accessor
(实际上是C函数)。
否则,解决这个问题的一个非常真实的方法是检查ActiveStorage::Attachment.instance_methods.include?(:url)
和猴子补丁/包含/前置不存在时。