【问题标题】:how do I render @photo.errors with json (using dropzone.js in Rails 4)如何使用 json 渲染 @photo.errors(在 Rails 4 中使用 dropzone.js)
【发布时间】:2016-12-27 15:17:54
【问题描述】:

Heroku 控制台:

开始 POST "/photos"
由 PhotosController 处理#create as JSON
参数:{"utf8"=>"✓", "authenticity_token"=>"D5pc72xeJ6J/g==", "photo"=>{"title"=>"ffffffffffffffffffffffffffffffffffffffffffffffffffffff", "tag_list"=>[""], "picture"=>#, @original_filename="size.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"photo[picture]\"; filename= \"size.jpg\"\r\nContent-Type: image/jpeg\r\n">}, "null"=>"", "commit"=>"Upload"}
Completed 500 Internal Server Error in 941ms (ActiveRecord: 13.9ms)
ArgumentError ('#, @messages={:title=>["is too long (maximum is 30 characters)"]}>' is not一个 ActiveModel 兼容的对象。它必须实现 :to_partial_path。):
app/controllers/photos_controller.rb:40:in `block (2 levels) in create'

照片控制器

def create
  @photo = current_user.photos.build(photo_params)
    respond_to do |format|
      if @photo.save
        format.html { redirect_to @photo, notice: 'Item was successfully created.' }
        format.json { render json: @photo }
      else 
        format.html { render 'new'}
        **rb:40** (format.json { render @photo.errors, status: :unprocessable_entity } 
      end
    end
end

dropzonephotos.js

$(document).ready(function() {
  var dropzone;
  Dropzone.autoDiscover = false;
  dropzone = new Dropzone('#dropform', {
    maxFiles: 2,
    maxFilesize: 3,
    paramName: 'photo[picture]',
    headers: {
      "X-CSRF-Token": $('meta[name="csrf-token"]').attr('content')
    },
    addRemoveLinks: true,
    clickable: '.dz-default.dz-message',
    previewsContainer: '.dz-default.dz-message',
    thumbnailWidth: 200,
    thumbnailHeight: 200,
    parallelUploads: 100,
    autoProcessQueue: false,
    uploadMultiple: false
  });
  $('#item-submit').click(function(e) {
    e.preventDefault();
    e.stopPropagation();
    if (dropzone.getQueuedFiles().length > 0) {
      return dropzone.processQueue();
    } 
    else {
      return $('#dropform').submit();
    }

  });
  return dropzone.on('success', function(file, responseText) {
    return window.location.href = '/photos/' + responseText.id;
  });
  return dropzone.on('error', function(file, errorMessage, xhr) {
    console.log('error');
  });
});

验证失败时,视图中不会呈现任何错误。拖放区缩略图上只有一个“X”,悬停时显示“内部服务器错误”消息。缩略图仍然显示在视图中,尽管它实际上已经被删除了。如果我再次单击提交,表单将作为 html 处理,因为 dropzone 中没有照片/没有要提交的 json。

【问题讨论】:

标签: ruby-on-rails json dropzone.js


【解决方案1】:

所以我决定不用担心表单内部的 Rails Active Record Validation Errors 这样做,这甚至可能是不可能的,因为表单是由 json 提交的,而且 Rails 帮助程序可能没有设置为以这种方式工作,我决定通过将错误附加到视图中来手动使用 dropzone.on('error', function(file, errorMessage) 内的 .js 文件本身进行操作。

【讨论】:

    猜你喜欢
    • 2014-02-18
    • 2014-12-20
    • 1970-01-01
    • 1970-01-01
    • 2013-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-20
    相关资源
    最近更新 更多