The file uploading is working properly using ruby on rails. Now i need to validate my uploading. It should validate and display error message when no file is selected after clicking upload. Please help me with a code for this error validation.
My view file is (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%>
My controller file is (upload_controller.rb):
class UploadController < ApplicationController
def uploadFile
post = DataFile.save(params[:upload])
render :text => "File has been uploaded successfully"
end
end
My model file is (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