Rails 5.1如何在format.json中呈现无内容响应

时间:2017-07-19 15:34:18

标签: ruby-on-rails json controller

我已经查看了至少10个关于此的问题,并尝试了所有内容(例如像this question),但没有一个建议有效,例如:

例如:

format.json head :no_content and return

抛出此错误:

ArgumentError (wrong number of arguments (given 2, expected 1)):

虽然这个:

format.json head and return

抛出此错误:

ArgumentError (wrong number of arguments (given 0, expected 1..2)):

这是我目前在控制器操作中所拥有的:

def paid
    @user = User.find_by(id: session['user_id'])
    respond_to do |format|    
      if !@user.nil?
        @user.is_paid = true
        @user.payment_reference = payment_params[:reference]
        @user.save
        format.json { render head, status: :no_content } and return
      else
        format.json render json: { message: "failed to record payment" }, status: :unprocessable_entity
      end
    end
  end

这可行,但在控制台中抛出错误:

No template found for PaymentsController#paid, rendering head :no_content

我不想添加一个空模板来解决这个问题。我想告诉Rails我想渲染头:no_content!

This question表明在Rails 3.1中,默认生成的代码执行了此操作:

format.json { head :no_content }

但是在日志中显示的确是相同的错误。

1 个答案:

答案 0 :(得分:3)

因此,事实证明这个动作是从ajax请求调用的,就像这样(注意没有指定dataType):

    $.ajax({
        type : 'POST',
        beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},  
        url : '/payments/paid',
        data: JSON.stringify(paymentObject),
        contentType: 'application/json; charset=utf-8',
        success: record_payment_success,
        error: function() {
          console.log('Error recording payment in db');
        }
    });

因此,如果我在rails中执行此操作,则有关缺少模板的错误将消失:

    format.js { head :no_content }

所以js响应很好,所以如果我把ajax更改为:

    $.ajax({
        type : 'POST',
        beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},  
        url : '/payments/paid',
        data: JSON.stringify(paymentObject),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: record_payment_success,
        error: function() {
          console.log('Error recording payment in db');
        }
    });

然后这适用于Rails:

    format.json { head :no_content }

我收到了204 No Content响应,日志中没有错误。

Started POST "/payments/paid" for 127.0.0.1 at 2017-07-19 18:05:31 +0200
Processing by PaymentsController#paid as JSON
  Parameters: {"payment"=>{"reference"=>"PAY-76D56139RT7576632LFXYGPA"}}
Completed 204 No Content in 181ms (ActiveRecord: 26.9ms)