2016-01-23 82 views
3

我測試下面的方法:如何在json中不渲染任何東西?

def destroy 
    if @article.destroy 
     render json nothing: true, message: "removed", status: :ok 
    else 
     render json: @article, message: "Failed to remove", status: :bad_request 
    end 
    end 

render json nothing線生成錯誤爲#API

未定義的方法`JSON」 :: V1 :: ArticlesController:0x000000074f6148

將行更改爲render json: message: "removed", status: :ok沒有區別。如何不渲染?

更新:我試了下面的代碼,刪除後迴應No response received,而我期望的消息。

def destroy 
    if @article.destroy 
     respond_to do |format| 
     format.json { render nothing: true, message: "removed", status: :ok } 
     end 
    else 
     render json: @article, message: "Failed to remove", status: :bad_request 
    end 
    end 

回答

8

如果你真的想不呈現任何內容:

head :ok 

如果您想發送一個JSON消息作爲迴應:

render json: { message: "removed" }, status: :ok 
+1

謝謝,有也只能以此爲JSON的方法嗎? – Marty

+0

它是有道理的,但對我來說,這呈現:'沒有收到任何答覆'(它已刪除文章)。我希望看到這個消息。 – Marty

+0

爲了確保我做得正確,我添加了用於OP的代碼。 – Marty

4

返回HTTP 204無內容將使如果你不想返回任何東西,那更有意義。

render :nothing => true, :status => 204 

或者更好的只是:

head :no_content 
+0

謝謝,它的工作原理。我想這是不可能在同一時間顯示一條消息(在序列化程序中包含屬性)? – Marty

相關問題