1

我正在使用 Rails 和 RABL 创建一个 json api。

有没有办法使用 RABL 显示自定义错误消息?

例如,这个想法是在找不到对象而不是标准模板时将错误消息显示为 json,例如它显示消息:

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

例如,我尝试使用以下代码在 API 中显示自定义错误消息:

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

在我的 Show RABL 模板中:

object @foo

attributes :id, :name

node :errors do |o|
    o.errors
end

这样做我收到了 RABL 模板的错误消息,而不是正确的 json:

undefined method `errors' for nil:NilClass
4

1 回答 1

2

对于您的错误状态,您应该使用render而不是respond_with.

render(:json => errors.to_json, :status => 404)
于 2013-09-26T05:33:15.517 回答