簡體   English   中英

在rails中的ruby中上傳文件時出現錯誤消息

[英]error message when uploading file in ruby on rails

使用Rails上的ruby可以正常上傳文件。 現在我需要驗證我的上傳。 單擊上傳后未選擇文件時,它將驗證並顯示錯誤消息。 請幫助我提供用於此錯誤驗證的代碼。

我的查看文件是(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

如果您使用回形針寶石,則可以在模型中這樣做。

validates_attachment_presence :datafile unless :datafile

它檢查上載文件的存在。

更新

要顯示錯誤消息,只需將此行添加到表單中

<%= error_messages_for :upload_file %> #Assuming your model name is `upload_file`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM