2

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
2
  • if in case you want to handle in controller action use if params[:upload].present? and params[:upload][:datafile].present? Commented Apr 8, 2014 at 11:03
  • @Nithin i need to show alert message like "no file chosen please choose file" after clicking upload Commented Apr 8, 2014 at 12:12

1 Answer 1

1

If you are using paperclip gem,you can do like this in your Model.

validates_attachment_presence :datafile unless :datafile

It checks the existence of uploaded file.

Update

For displaying the error messages,just add this line to your form

<%= error_messages_for :upload_file %> #Assuming your model name is `upload_file`
Sign up to request clarification or add additional context in comments.

15 Comments

everything good.but i need the error message should be displayed when no file is chosen.
i'm getting this error " undefined method `error_messages_for' for #<#<Class:0x3217050>:0x2a9b1f0> "
i posted my full coding
@user3279260 Try moving this line <%= error_messages_for :data_file %> just below the form_tag line
@user3279260 Now i get it.Its because you added the validation in the wrong model.it should be in Upload model.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.