Rails ActiveStorage存储到特定路径



有没有办法为活动存储文件创建更具体的路径?我需要什么:目前,我们在/storage中存储一些内容,但我们希望以更多维的方式存储这些文件。例如,user_files/#{Apartment::Tenant.current}/people/#{user_id}

以下是我在activestorage 6.0.21和activestorage_direct_disk 0.3.2上的工作原理,也是基于如何向activestorage添加自定义服务。AS一直是";改进的";与此同时,你可能会想出一种不同的方法来做这件事,但如果几周后你对尝试让它发挥作用感到沮丧和厌倦,你可能可以求助于这样的方法:

# lib/set_direct_disk_service_path.rb
module SetCurrentDomainName
def set_domain_name(d)
self.domain_name = d
end
end
ActiveStorage::Current.class_eval { include SetCurrentDomainName }
module SetDirectDiskServiceRoot
def initialize(p:, public: false, **options)
@root = Rails.root.join("public", p)
@public_root = p
@public_root.prepend('/') unless @public_root.starts_with?('/')
end
def current_domain_name
ActiveStorage::Current.domain_name
end
def folder_for(key)
# output your path here.
end
end

您可以在before_action钩子中的ApplicationController中设置不同的变量。我使用了自己的多租户方案,因为公寓不符合要求,所以我从应用程序控制器中传递租户域名。

最新更新