Nei*_*eil 22 ruby ruby-on-rails rails-activestorage
我需要获取正在使用的磁盘上的文件的路径ActiveStorage
.该文件存储在本地.
当我使用paperclip时,我path
在附件上使用了返回完整路径的方法.
例:
user.avatar.path
Run Code Online (Sandbox Code Playgroud)
在查看Active Storage Docs时,它似乎rails_blob_path
可以解决问题.在查看它返回的内容之后,它没有提供文档的路径.因此,它返回此错误:
没有这样的文件或目录@ rb_sysopen -
背景
我需要文档的路径,因为我使用的是combine_pdf gem,以便将多个pdf组合成一个pdf.
对于回形针实现,我迭代了所选pdf附件的full_paths,并将load
它们组合成合并的pdf:
attachment_paths.each {|att_path| report << CombinePDF.load(att_path)}
Run Code Online (Sandbox Code Playgroud)
小智 23
只需使用:
ActiveStorage::Blob.service.send(:path_for, user.avatar.key)
Run Code Online (Sandbox Code Playgroud)
您可以在模型上执行以下操作:
class User < ApplicationRecord
has_one_attached :avatar
def avatar_on_disk
ActiveStorage::Blob.service.send(:path_for, avatar.key)
end
end
Run Code Online (Sandbox Code Playgroud)
eco*_*gic 10
我不确定为什么其他所有答案都使用send(:url_for, key)
。我使用的是Rails 5.2.2,它url_for
是一个公共方法,因此最好避免使用send
或直接调用path_for
:
class User < ApplicationRecord
has_one_attached :avatar
def avatar_path
ActiveStorage::Blob.service.path_for(avatar.key)
end
end
Run Code Online (Sandbox Code Playgroud)
值得注意的是,您可以在视图中执行以下操作:
<p>
<%= image_tag url_for(@user.avatar) %>
<br>
<%= link_to 'View', polymorphic_url(@user.avatar) %>
<br>
Stored at <%= @user.image_path %>
<br>
<%= link_to 'Download', rails_blob_path(@user.avatar, disposition: :attachment) %>
<br>
<%= f.file_field :avatar %>
</p>
Run Code Online (Sandbox Code Playgroud)
感谢@muistooshort在评论中的帮助,在查看Active Storage Code之后,这有效:
active_storage_disk_service = ActiveStorage::Service::DiskService.new(root: Rails.root.to_s + '/storage/')
active_storage_disk_service.send(:path_for, user.avatar.blob.key)
# => returns full path to the document stored locally on disk
Run Code Online (Sandbox Code Playgroud)
这个解决方案对我来说有点不舒服.我很想听听其他解决方案.这对我有用.
小智 5
您可以将附件下载到本地目录,然后进行处理。
假设您的模型中有:
has_one_attached :pdf_attachment
Run Code Online (Sandbox Code Playgroud)
您可以定义:
def process_attachment
# Download the attached file in temp dir
pdf_attachment_path = "#{Dir.tmpdir}/#{pdf_attachment.filename}"
File.open(pdf_attachment_path, 'wb') do |file|
file.write(pdf_attachment.download)
end
# process the downloaded file
# ...
end
Run Code Online (Sandbox Code Playgroud)