Question

I'm creating a json api using Rails and RABL.

Is there any way to show custom errors messages using RABL?

The idea for example, is to show an error message as json when can't find an object instead of the standard template, for example it shows the message:

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

For example, I'm trying to show a custom error message in the API using the following code:

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

And in my Show RABL template:

object @foo

attributes :id, :name

node :errors do |o|
    o.errors
end

Doing this I'm getting the an error message for the RABL template instead of the right json:

undefined method `errors' for nil:NilClass
Was it helpful?

Solution

For your error state you should use render instead of respond_with.

render(:json => errors.to_json, :status => 404)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top