如何从远程提交的表单返回JSON表单中的验证错误?

时间:2016-06-08 20:51:41

标签: json ajax forms ruby-on-rails-4 validationerror

我正在使用Rails 4.2.3和“:remote =>真正的“远程提交表单的属性。但是,我在显示返回的验证错误时遇到问题。在我的控制器中我有

  def create
    @my_object = MyObject.new(my_object_params)
    @current_user = User.find(session["user_id"])
    @my_object.user = @current_user
    @date = Date.strptime(my_object_params[:day], "%m/%d/%Y")
    @my_object.day = @date
    respond_to do |format|
      if @my_object.save
        flash[:notice] = 'Saved successfully'
        format.html { redirect_to controller: "users", action: "index", notice: 'Saved successfully.' }
        format.js { render js: "window.location='/users'" }
      else
        format.html { render action: "index" }
        format.json { render json: @my_object.errors, status: :unprocessable_entity }
        format.js { render json: { error: @my_object.errors, success: false }, content_type: 'application/json' }
      end
    end
  end

在我的咖啡脚本中,我有

$(document).ready (data) ->
  $("#add_form").bind "ajax:error", (xhr, status, error) ->
    console.log(xhr) 
    console.log(status)
    console.log(error)
    render_form_errors(xhr, error)
    #Give an alert message
  $("#add_form").bind "ajax:before", (evt, data, status, xhr) ->
    hrs = $('#my_object_hour').val();
    min = $('#my_object_minute').val();
    sec = $('#my_object_second').val();
    $('#my_object_my_object_times_attributes_0_time_in_ms').val((hrs * 60 * 60 + min * 60 + sec) * 1000);

但是三个字段“xhr,status,error”中没有一个包含JSON错误。 console.log语句的输出是

j…y.Event {type: "ajax:error", timeStamp: 1465418664628, jQuery112103593207809583596: true, isTrigger: 3, namespace: ""…}
users.self-a27ba2c….js?body=1:13 Object {readyState: 4, responseText: "ArgumentError in MyObjectsController#create↵↵invalid d…VER_PROTOCOL: "HTTP/1.1"↵↵Response headers↵None↵↵", status: 500, statusText: "Internal Server Error"}
users.self-a27ba2c….js?body=1:14 error

如何从控制器传回这些信息?

谢谢, -

编辑:为了回答答案,我按照指定的方式编辑了控制器,并将其添加到我的咖啡脚本中......

$(document).ready (data) ->
  $("#add_form").bind "ajax:failure", (e, xhr, status, error) -> 
    console.log('error');
    console.log(e);
    console.log(xhr);
    console.log(status);
    console.log(error);
    render_form_errors(xhr, error)  
  $("#add_form").bind "ajax:error", (xhr, status, error) ->
    console.log(xhr)
    console.log(status)
    console.log(error)
    render_form_errors(xhr, error) 
    #Give an alert message
  $("#add_form").bind "ajax:before", (evt, data, status, xhr) ->
    hrs = $('#my_object_hour').val();
    min = $('#my_object_minute').val();
    sec = $('#my_object_second').val();
    hrs_in_ms = hrs * 60 * 60 * 1000
    min_in_ms = min * 60 * 1000
    sec_in_ms = sec * 1000
    ms = hrs_in_ms + min_in_ms + sec_in_ms
    alert(ms)
    $('#my_object_my_object_times_attributes_0_time_in_ms').val(ms);

但在提交有错误的表单时,上述所有内容都不会被调用。我知道有错误,因为我看到(通过调试)" else" " if @ my_object.save"被召唤。

1 个答案:

答案 0 :(得分:1)

首先,您需要修复500错误,我没有采用您的示例,但这只是一个粗略的例子。

bugs.js

$(document).ready(function() {
  console.log('hiii');
  $('#new_bug')

  .on('ajax:success', function(e, data, status, xhr) {
    console.log('success');
    console.log(e);
    console.log(data);
    console.log(status);
    console.log(xhr);
  })

  .on('ajax:error', function(e, xhr, status, error) {
    console.log('error');
    console.log(e);
    console.log(xhr);
    console.log(status);
    console.log(error);
  })
})

在您的控制器中,例如我的控制器是 bugs_controller.js

  def create
    @bug = Bug.new(bug_params)

    respond_to do |format|
      if @bug.save
        format.html { redirect_to @bug, notice: 'Bug was successfully created.' }
        format.json { render :show, status: :created, location: @bug }
        format.js { render json: { success: true, bug: @bug.to_json }, content_type: 'application/json' }
      else
        format.html { render :new }
        format.json { render json: @bug.errors, status: :unprocessable_entity }
        format.js { render json: { error: @bug.errors, success: false }, content_type: 'application/json' }
      end
    end
  end

如果您希望对其他人阻止ajax:error回调,则需要提供不同的状态代码,例如400,500。 format.js { render json: { error: @bug.errors, success: false }, content_type: 'application/json', status: 500 },虽然我不会真的推荐这个,因为这不是正确的方法。您的ajax:success会处理验证错误,因为我们正在通过success: false,我们可以检查js中是否存在验证错误。