【问题标题】:Change the path for saving file using paperclip/rails使用回形针/导轨更改保​​存文件的路径
【发布时间】:2016-08-04 15:32:16
【问题描述】:

我正在制作 Rails 应用程序并使用回形针将文件上传到 AWS S3 存储桶。 在我的模型中,我配置如下:

 class File < ApplicationRecord
    has_attached_file :attachment,
                                :url => "/sample_pdf/:basename.:extension",
                                :path => "/sample_pdf/:basename.:extension"

    validates_attachment :attachment,
                                         :content_type => {
                                                 :content_type =>
                                                         ["application/pdf"]
                                         }
end

我面临的问题是有时我需要将文件上传到"/sample_pdf/:basename.:extension",有时我需要上传到其他路径,例如"/another_pdf_folder/:basename.:extension"

我不确定是否可以根据我的需要更改存储文件的路径。

谢谢。

【问题讨论】:

    标签: ruby-on-rails amazon-s3 paperclip


    【解决方案1】:

    您可以通过模型中的方法设置路径来动态设置路径。

    class File < ApplicationRecord
        has_attached_file :attachment,
                   :url => "/sample_pdf/:basename.:extension",
                   :path => :attachment_dynamic_path,
                   validates_attachment :attachment,
                   :content_type => {
                                     :content_type =>  ["application/pdf"]
                                    }
      def attachment_dynamic_path
        condition ? "/sample_pdf/:basename.:extension" : "/another_pdf_folder/:basename.:extension"
      end
    end
    

    【讨论】:

    • 我对条件不是很熟悉。我应该采取哪种行动?有没有办法选择一个?
    • 您没有任何条件希望将文件保存在任一路径中吗?
    • 所以我还有另外两个不同的模型:ServiceA、ServiceB。每个模型都有很多File,所以我可以在每个服务下上传多个文件。取决于我使用的服务,路径应该改变。但我不确定如何在File 模型级别检查我将文件上传到哪个服务。
    • 所以路径将依赖于Service
    • 如果是这种情况,你也可以这样做,假设每个服务都有一个name:path =&gt; "/#{self.service.name}_pdf/:basename.:extension"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-08
    • 1970-01-01
    • 2016-08-28
    • 1970-01-01
    • 2014-04-11
    • 1970-01-01
    • 2020-05-17
    相关资源
    最近更新 更多