Carrierwave错误消息未显示

时间:2015-02-05 08:55:14

标签: ruby validation ruby-on-rails-4 activerecord carrierwave

我有一个通过ajax调用上传文件的表单(使用remotipart gem),不确定这是否相关但是当验证失败并且文件类型(使用carrierwave白名单)时,我无法得到错误即使显示其他错误消息(例如文件大小很大),也要在视图中显示消息。

所以在我的Uploader类中

class MediaUploader < CarrierWave::Uploader::Base
  def extension_white_list
    %w(jpg jpeg gif png docx mp4 pdf)
  end
end

因此,在我的表单中,我将附加一个csv文件,点击提交,请求和响应看起来像这样

Processing by DocumentsController#create as JS
Parameters: {"utf8"=>"✓", 
             "document"=>
                {"skill_id"=>"1",
                 "media_cache"=>"",
                 "media"=>#<ActionDispatch::Http::UploadedFile:0x000000070157a0 @tempfile=#<Tempfile:/tmp/RackMultipart20150205-4409-ltyy7t.csv>,              @original_filename="csvtest.csv", @content_type="text/csv", @headers="Content-Disposition: form-data; name=\"document[media]\"; filename=\"csvtest.csv\"\r\nContent-Type: text/csv\r\n">}, 
                 "commit"=>"Upload", 
                 "remotipart_submitted"=>"true",
                 "authenticity_token"=>"token here", 
                 "X-Requested-With"=>"IFrame", 
                 "X-Http-Accept"=>"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01"
             }

 (1.8ms)  BEGIN
 (2.7ms)  ROLLBACK

在我的控制器中,我抓住了错误消息@document.errors

#<ActiveModel::Errors:0x0000000666e418 
@base=#
  <Document id: nil, 
            media: nil, 
            user_id: 1, 
            skill_id: 1, 
            created_at: nil, 
            updated_at: nil>, 

            @messages={:media=>[
                                "You are not allowed to upload \"csv\" files, allowed types: jpg, jpeg, gif, png, docx, mp4, pdf", 
                                "At least 1 File is required"
                               ]
                      }>

在此之后调用相关的控制器操作/视图

Rendered documents/_document_form.html.erb (5.1ms)
Rendered documents/create.js.erb (7.7ms)
Completed 200 OK in 167ms (Views: 83.2ms | ActiveRecord: 64.6ms)

我的表单是为了遍历每个错误消息但但它没有显示它们

_document_form

 <%= form_for @document, remote: true, html: { multipart: true, id: @document.object_id.to_s, class: 'upload_document' } do |f| %>
  <% if @document.errors.any? %>
    <h2><%= pluralize(@document.errors.count, "error") %> prohibited this record from being saved</h2>
      <ul class="error_list">
        <% @document.errors.full_messages.each do |msg| %>
          <li><%= error_edit(msg) %></li>
        <% end %>
      </ul>
  <% end %>

  <%= f.hidden_field :skill_id %>

  <%= f.label :media %>

  <%= f.file_field :media %> 

  <%= f.submit 'Upload', class: 'btn btn-success' %>
  <div class="js-error"></div>

<% end %>

创建行动

def create
@document = current_user.documents.new(document_params)
respond_to do |format|

   if @document.save
     format.html { redirect_to root_path, notice: success_save_msg }
     #format.js { render :js => "window.location.href='"+root_path+"'", notice: success_save_msg }
   else
     format.html
     format.js { render action: 'create.js.erb' }
     ap(@document.errors)
   end

end
end

create.js.erb

$("#<%= @document.skill_id %>").html("<%= j render(partial: 'documents/document_form', locals: { skill_id: @document.skill_id }) %>")

此外,我正在查看网络标签中的回复,并且明确返回错误消息:

<textarea data-type="text/javascript" data-status="200" data-statusText="OK">$
("#1").html("<\n<form id=\"55100200\" class=\"upload_document\" enctype=\"multipart/form-data\" action=\"/documents\" accept-charset=\"UTF-8\" data-remote=\"true\" method=\"post\"><input name=\"utf8\" type=\"hidden\" value=\"&#x2713;\" />\n    <div id=\"error_explanation\" class=\"alert alert-dismissable\">\n      <button type=\"button\" class=\"close\" data-dismiss=\"alert\"><span aria-hidden=\"true\">&times;<\/span><span class=\"sr-only\">Close<\/span><\/button>\n      <h2>2 errors prohibited this record from being saved<\/h2>\n        <ul class=\"error_list\">\n            <li>  You are not allowed to upload &quot;csv&quot; files, allowed types: jpg, jpeg, gif, png, docx, mp4, pdf<\/li>\n            <li>  At least 1 File is required<\/li>\n        <\/ul>\n    <\/div>\n\n  <input value=\"1\" class=\"skill_id\" type=\"hidden\" name=\"document[skill_id]\" id=\"document_skill_id\" />\n\n  <label class=\"custom-file-upload btn btn-info\" for=\"document_media_60835260\">\n    <span class=\"glyphicon glyphicon-cloud-upload\"><\/span>\n     Find File\n<\/label>\n  <input class=\"document_file_field\" id=\"document_media_60835260\" type=\"file\" name=\"document[media]\" />\n  <input type=\"hidden\" name=\"document[media_cache]\" id=\"document_media_cache\" />\n\n  <input type=\"submit\" name=\"commit\" value=\"Upload\" class=\"btn btn-success\" />\n  <div class=\"js-error\"><\/div>\n\n<\/form>")
</textarea>

任何人都可以看到为什么来自carrierwave时不会显示错误消息,而不是来自我的Document模型中的验证?

2 个答案:

答案 0 :(得分:3)

以为我会分享这个,所以如果其他人有同样的问题,它可能会有所帮助。我偶然发现了这个Blog。这导致我This stackoverflow post

原来我只需要在我的en.yml文件中设置消息(或者我想要的自定义消息),其余的就是载波完成

en:
  errors:
    messages:
      extension_white_list_error: 'My Custom Message'

希望这有助于某人

答案 1 :(得分:0)

多数民众赞成我的en.yml

   en:
      hello: "Hello world"
      errors:
        messages:
          extension_white_list_error: 'My Custom Message'

enter image description here

编辑这修复了我的脚本

en:
  # hello: "Hello world"
  errors:
    messages:
      extension_whitelist_error: "You are not allowed to upload %{extension} files, allowed types: %{allowed_types}"