如何创建下载链接

ten*_*ns6 10 ruby-on-rails ruby-on-rails-3

创建下载链接的最佳方法是什么?有没有比以下更好的方法?

我想link_to "Download", :controller => ..., :action => ...", :id => ...在视图中使用.

添加match /documents/download/:id => documents#download到routes.rb

在控制器中:

def download
  send_file ...
end 
Run Code Online (Sandbox Code Playgroud)

此外,如果可能,我希望用户与链接保持在同一页面上.

谢谢.

Pre*_*her 7

我将下载操作添加为资源块中的restful路由.这是我的典型代码:

的routes.rb

  resources :things do
    member do
      get :download
    end
  end    
Run Code Online (Sandbox Code Playgroud)

模型:

  has_attached_file :document,
    :path => ':rails_root/assets/documents/:id/:basename.:extension'
  attr_protected :document_file_name, :document_content_type, :document_file_size
Run Code Online (Sandbox Code Playgroud)

控制器:

  def download
    send_file @thing.document.path, :type => 'application/pdf', :filename => @thing.permalink
  end
Run Code Online (Sandbox Code Playgroud)

视图:

  <%= link_to 'Download', download_thing_path(@thing) %>
Run Code Online (Sandbox Code Playgroud)

这使用户保持在同一页面上,并使用我建议的名称启动下载(我使用永久链接).

动态生成是什么意思?它们是由您上传还是由您的应用程序即时创建的?