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



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

例如:

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!

这个问题表明,在 Rails 3.1 中,默认生成的代码是这样做的:

format.json { head :no_content }

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

所以,事实证明这个动作是从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',
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 无内容响应,并且日志中没有错误。

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)

最新更新