2013-06-27 1 views
1

레일즈와 RABL을 사용하여 json api를 만들고 있습니다.레일즈에서의 에러 핸들링을 위해 RABL 사용하기 json

RABL을 사용하여 맞춤 오류 메시지를 표시 할 수있는 방법이 있습니까?

예를 들어 아이디어, 그것은 메시지를 보여줍니다 예를 들어 대신에 표준 템플릿의 객체를 찾을 수없는 JSON과 같은 오류 메시지를 보여주는 것입니다

:

{"errors":"Foo that you were looking for could not be found."} 

예를 들어, 난을

class Api::V1::FooController < ApplicationController 
respond_to :json 
before_filter :find_foo, :only =>[:show] 

    def find_foo 
     @foo = Foo.find(params[:id]) 
     rescue ActiveRecord::RecordNotFound 
      @errors = { :errors => "Foo that you were looking for could not be found."} 
      respond_with(errors.to_json, :status => 404) 
    end 

    def show 
     respond_with(@foo) 
    end 
end 

그리고 내보기 RABL 템플릿 :

object @foo 

attributes :id, :name 

node :errors do |o| 
    o.errors 
end 
다음 코드를 사용하여 API에서 사용자 지정 오류 메시지를 보여 주려

내가 대신 올바른 JSON의 RABL 템플릿에 대한 오류 메시지를 받고 있어요 이렇게 :

undefined method `errors' for nil:NilClass 

답변

2

당신의 오류 상태를 들어 당신은 render 대신 respond_with 사용해야합니다.

render(:json => errors.to_json, :status => 404)