error message when uploading file in ruby on rails

大城市里の小女人 提交于 2019-12-13 00:23:26

问题


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

回答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`


来源:https://stackoverflow.com/questions/22934199/error-message-when-uploading-file-in-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!