2012-07-27 41 views
6

我需要我的用戶上傳他們的個人資料上的文檔,如廣告pdf和txt。我使用Carrierwave做到了這一點,所以我有一份包含標題和網址的文檔列表。Rails:如何下載以前上傳的文檔?

但我怎樣才能讓其他用戶下載這些文件?我是否必須使用寶石,或者是否有本地的我不知道,因爲我是非常新的軌道?

感謝

編輯:

society.rb

class Society < ActiveRecord::Base 
    ... 
    has_many :documents, :dependent => :destroy 
end 

document.rb

class Document < ActiveRecord::Base 
    belongs_to :society  
    mount_uploader :url, DocumentUploader  
end 

然後在此我要下載文件的視圖:

<% @society.documents.each do |doc| %> 
    <%= link_to "Download it", doc.url %> //url is the column name of the saved url 
    <% end %> 
+0

也許愚蠢的問題:如何處理您提到的網址給其他用戶? – Romain 2012-07-27 14:54:37

+0

對不起,我不明白你的意思=) – Barbared 2012-07-27 15:01:43

+1

請參閱@ anthonyalberto的回答。 – Romain 2012-07-27 15:04:00

回答

8

我不使用Carrierwave,但我想它與Paperclip相似。

因此,你應該能夠使用這樣的

link_to 'Download file', user.file.url 

這是假設你有從模型以「文件」 carrierwave屬性的用戶實例化對象。將其替換爲您的屬性名稱。

+0

我試過了,但我不工作,我確定我錯了。 我確實像你說過的,(請參閱上面編輯的問題) – Barbared 2012-07-27 15:12:19

+0

然後嘗試'doc.url.url',因爲你的屬性是'url',你必須調用它的方法'url'。希望'url'不會被carrierwave保留,否則,請更改您的mount_uploader屬性的名稱 – 2012-07-27 15:33:37

+0

Ahhh非常感謝您的支持! ^^ – Barbared 2012-07-27 15:40:57

8

您可以使用send_file這個方法。可能如下所示:

class MyController 
    def download_file 
    @model = MyModel.find(params[:id]) 
    send_file(@model.file.path, 
      :filename => @model.file.name, 
      :type => @model.file.content_type, 
      :disposition => 'attachment', 
      :url_based_filename => true) 
    end 
end 

查看apidock鏈接以獲取更多示例。

+0

我正在使用Carrierwave寶石,當我下載文件,如果該文件名包含空間,那麼它被轉換爲下劃線。那麼如何在下載時從文件名中刪除下劃線? – 2016-03-30 10:39:56

+1

@huzefa嘗試在文件名字符串上調用.humanize – NathanTempelman 2017-05-11 00:24:42