2012-11-27 4 views
17

사용자가 JSON을 Rails 3 앱의/update/action에 게시 할 때 응답하는 가장 좋은 방법은 무엇입니까? Rails 3에서 빈 JSON 응답을 반환하는 가장 좋은 방법은 무엇입니까?

난 그냥 ( How to return HTTP 204 in a Rails controller에서 예)

head :no_content 

또는

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

처럼 뭔가를 200 코드와 빈 JSON 응답을 보내려고합니다.

render :json => {} 

또는

render :json => 'ok' 

이 거기 선호 이상 레일-Y 방법 : 일반적으로

나는이 일이 있었나?

+0

204로 무엇이든 돌려 보내면 안됩니다. – Evert

+2

방금 ​​사용했습니다. head : ok –

답변

27

My Rails 3 앱은 이와 같은 코드를 업데이트 용으로 사용합니다. html과 xml 용 코드는 Rails에서 자동 생성되었으므로 동일한 형식을 사용하여 JSON 렌더러에 추가했습니다.

respond_to do |format| 
    if @product.update_attributes(params[:product]) 
    format.html { redirect_to(@product, :notice => 'Product was successfully updated.') } 
    format.xml { head :ok } 
    format.json { head :ok } 
    else 
    format.html { render :action => "edit" } 
    format.xml { render :xml => @product.errors, :status => :unprocessable_entity } 
    format.json { render :json => @product.errors, :status => :unprocessable_entity } 
    end 
end 

완벽하게 작동합니다. 이것이 궁극적으로 중요합니다.

+0

head : no_content와 head : ok의 차이점은 무엇입니까? – Donato

+1

@Donato a : no_content (204) 응답은 성공했지만 내용을 반환하지 않은 요청입니다. ok (200)는 성공했지만 여전히 적절한 데이터를 반환하는 요청입니다. –

관련 문제