2016-08-04 106 views
1

我在製作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"

我不確定是否有方法來改變存儲文件的路徑取決於我的需要。

感謝。

回答

0

您可以通過設置模型中的方法來動態設置路徑。

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 
+0

我對條件不是很熟悉。我應該採取哪一種行動?有沒有辦法選擇一個? – JoHksi

+0

你沒有任何條件的基礎上,你想保存文件的任何路徑? – titan

+0

所以我有兩個不同的模型:ServiceA,ServiceB。每個模型都有很多'File',所以我可以在每個服務下上傳多個文件。取決於我使用的服務,路徑應該改變。但我不確定如何檢查我將文件上傳到「文件」模型級別的服務。 – JoHksi