2017-07-19 116 views
1

無響應的內容我已經看過這個至少10個問題,並想盡一切(比如像this question),但沒有建議工作,比如:的Rails 5.1如何呈現在format.json

這對例如:

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 [email protected]? 
     @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 } 

,但顯示在日誌中的完全相同的錯誤。

+0

嘗試'format.json {head:no_content}並返回' – Pavan

+0

謝謝,剛剛嘗試過,日誌中出現同樣的錯誤。 – rmcsharry

+0

嘗試'format.json {render head:no_content}' – Pavan

回答

3

所以,事實證明這一行動正在從一個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'); 
     } 
    }); 

所以,如果我這樣做在軌,失蹤的錯誤模板了:

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)