无法以最佳方式处理 HTTP 422 rails

unable to handle HTTP 422 with best in place rails

我的控制器代码是这样的:

def update
respond_to do |format|
  if refresh_quantity_in_inventory
    format.json { render json: { message: "Quantity successfully updated" } }
  else
    format.json { render json: @errors, status: :unprocessable_entity }
  end
end

结束

CoffeeScript 是这样的:

ready = ->
   $('#best_in_place_cart_quantity').best_in_place().bind 'ajax:error', (evt, data, status, xhr) ->
      alert xhr
      alert xhr.status
      if (xhr.status == 422)
        alert("Inventory count is not enough")
$(document).ready ready
$(document).on "page:load", ready

我也试过ajax:success,但都没有触发回调。我如何赶上422?我应该怎么办?


$('#best_in_place_cart_quantity').best_in_place().done((data, status, response) ->
    alert 'Done handler. HTTP code: ' + response.status
    return
  ).fail (error) ->
    alert 'Fail handler. HTTP code: ' + error.status
    return

这个也没用。

此代码示例展示了如何使用 JQuery(即 422)处理 HTTP 错误:

$.get('http://httpbin.org/status/422')
    .done(function(data, status, response) {
        alert('Done handler. HTTP code: ' + response.status);
    })
    .fail(function(error) {
        alert('Fail handler. HTTP code: ' + error.status);
    });  

Here 是这段代码的片段。

尝试采用上面的代码并将 ready 处理程序替换为:

$ ->
   // your code here

这是最终有效的代码。

$('.best_in_place_cart_quantity').best_in_place()

$(".best_in_place_cart_quantity").bind 'ajax:error',  (evt,  data,  status,  xhr) ->
    alert "Not enough quantity"

经验教训是,我们应该通过 class 而不是 Id 绑定最佳位置字段。