使用ruby on rails正确上传文件。现在我需要验证我的上传。单击上载后未选择文件时,应验证并显示错误消息。请帮我提供此错误验证的代码。
我的查看文件是(uploadfile.html.erb):
<h1>File Upload</h1>
<%= form_tag({action: :uploadFile}, multipart: true) do %>
<p><label for="upload_file">Select File</label>
<%= error_messages_for :data_file %>
<%= file_field 'upload', 'datafile' %></p>
<%= submit_tag "Upload" %>
<%end%>
我的控制器文件是(upload_controller.rb):
class UploadController < ApplicationController
def uploadFile
post = DataFile.save(params[:upload])
render :text => "File has been uploaded successfully"
end
end
我的模型文件是(data_file.rb):
class DataFile < ActiveRecord::Base
attr_accessor :upload
validates_attachment_presence :upload unless :upload
def self.save(upload)
name = upload['datafile'].original_filename
directory = "public/data"
# create the file path
path = File.join(directory, name)
# write the file
File.open(path, "wb") { |f| f.write(upload['datafile'].read) }
end
end
答案 0 :(得分:1)
如果您使用的是paperclip gem,则可以在模型中执行此操作。
validates_attachment_presence :datafile unless :datafile
检查上传文件是否存在。
<强>更新强>
要显示错误消息,只需将此行添加到表单
即可<%= error_messages_for :upload_file %> #Assuming your model name is `upload_file`