【问题标题】:Rails 5.1 how to render no content response in format.jsonRails 5.1 如何在 format.json 中呈现无内容响应
【发布时间】:2017-07-19 15:34:18
【问题描述】:

我已经查看了至少 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 我要渲染 head :no_content!

This question 表明在 Rails 3.1 中默认生成的代码是这样的:

format.json { head :no_content }

但这在日志中显示了相同的确切错误。

【问题讨论】:

  • 试试format.json {head :no_content} and return
  • 谢谢,刚试了下,同样的错误。
  • 试试format.json { render head :no_content }
  • 这会引发 AbstractController::DoubleRenderError 但如果我添加“并返回”,那么我会在日志中得到缺少的模板。
  • @Pavan 谢谢,你为我指明了正确的方向!

标签: ruby-on-rails json controller


【解决方案1】:

所以,事实证明这个动作是从一个 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-19
    • 1970-01-01
    • 1970-01-01
    • 2011-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-13
    相关资源
    最近更新 更多