2012-10-28 14 views
2

我試圖通過上傳文件(文件名,大小)來顯示可能發生的錯誤。 我正在使用an adapted version of Jquery Fiel Upload for Ruby on Rails如何將錯誤消息關聯到json響應中的'錯誤'鍵

我需要我的錯誤消息(驗證)關聯到我的json響應中的'錯誤'鍵。

我想我必須改變JavaScript來使它工作。

JSON:

render json: {error: @upload.errors.full_messages}, status: :unprocessable_entity 

驗證:

validates_uniqueness_of :upload_file_name, :message => "File with this name is already in the database" 

validates :upload_file_size, :inclusion => {:in =>10.megabytes..20.megabytes}, :message =>"Too big or too small" 

的Javascript我用上傳的文件:

<script type="text/javascript" charset="utf-8"> 
     $(function() { 
      // Initialize the jQuery File Upload widget: 
      $('#fileupload').fileupload(); 
      // 
      // Load existing files: 
      $.getJSON($('#fileupload').prop('action'), function (files) { 
      var fu = $('#fileupload').data('fileupload'), 
       template; 
      fu._adjustMaxNumberOfFiles(-files.length); 
      console.log(files); 
      template = fu._renderDownload(files) 
       .appendTo($('#fileupload .files')); 
      // Force reflow: 
      fu._reflow = fu._transition && template.length && 
       template[0].offsetWidth; 
      template.addClass('in'); 
      $('#loading').remove(); 
      }); 

     }); 
    </script> 

我都試過,以及那些事: json: => [{:error=> @upload.errors.full_messages }] } 使用此僅顯示驗證消息但我需要的狀態:以及

回答

0

這裏是溶液:

JSON:

format.json{ render json: {error: @upload.errors.full_messages}, :status =>422} 

的JavaScript(主代碼的截止值)

$('#fileupload').fileupload({  


     error: function(xhr){ 
      var errors = $.parseJSON(xhr.responseText).error 
      alert(errors)   
     } 
       });