2012-07-27 44 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