链接从路径下载文件

时间:2013-07-19 19:18:13

标签: ruby-on-rails

我的机器上有一个文件的路径,我想设置下载链接。这是我正在尝试的:

在我的模特中:

class Exam < ActiveRecord::Base
   attr_accessible :data, :full_path
   has_attached_file :image,
      :path => :full_path
end

我的控制器看起来像这样:

def download
   @exam = Exam.find(params[:id])
   send_file @exam.image.path, :x_sendfile => true 
end

我的观点:

<%= link_to "Download", download_exam_path(@exam) %>

现在,当我点击下载时,我收到此错误:can't convert nil into String 我知道:full_path包含我文件的正确路径这一事实。我该如何解决这个问题?

完整错误:

 TypeError in ExamsController#download

can't convert nil into String

Rails.root: /Users/Ryan45/Programming/rails_projects/oldV_rails_project
Application Trace | Framework Trace | Full Trace

app/controllers/exams_controller.rb:83:in `download'

Request

Parameters:

{"id"=>"392"}

Show session dump

Show env dump
Response

Headers:

None

1 个答案:

答案 0 :(得分:1)

在您的视图中,@exam听起来像nil。可能是因为直到download操作内部才对其进行实例化 - 但您尝试在indexshow操作中使用它,但尚未构建它

如果是这种情况,那么你只需要添加它(或类似的东西 - 我不确定params[:id]是否可用于其他操作,因为它在{{1动作导致错误:

download

<强>更新

根据更新显示完整错误指向@exam = Exam.find(params[:id]) 的第83行,您在评论中确认为:

exams_controller.rb

我打开Rails控制台(send_file @exam.image.path, :x_sendfile => true ),然后输入:

rails c

然后我会通过尝试这两行开始检查以查看@exam = Exam.find(params[:id]) 的哪个部分@exam

  1. nil
  2. @exam.image
  3. 您可以根据该测试找出问题。

相关问题