我正在尝试将文件作为附件上传到电子邮件。当我尝试上传时,出现错误
“ nil:NilClass的未定义方法`original_filename'”我在做什么错了?
我需要从控制器中捕获文件,并在params [:file]不存在的情况下处理异常?
在我看来,有一个简单的上传文件标签
%strong Send Email with PDF attachment:
= file_field_tag :file
我需要从控制器中捕获文件, 这是我的控制器。
@name = params[:file].original_filename
if params[:file].present?
directory = "public/data"
path = File.join(directory, @name)
uniq_name = (0...10).map {(65 + rand(26)).chr}.join
time_footprint = Time.now.to_formatted_s(:number)
File.open(path, "wb") do |file|
file.write(params[:file].read)
@uniq_path = File.join(directory, uniq_name + time_footprint + File.extname(file))
File.rename(file, @uniq_path)
end
else
flash[:notice] = "You are going to send email without the invoice"
redirect_to update_estimate_job_final_invoices_path(@ticket)
end
答案 0 :(得分:0)
第一行是@name = params[:file].original_filename
。如果不存在params[:file]
,则对original_filename
的调用将失败。在if语句内移动该行:
if params[:file].present?
@name = params[:file].original_filename
directory = "public/data"
path = File.join(directory, @name)
...
else
...
end