Overriding the JSON response of respond_with for errors

788 Views Asked by At

I want to customize the error response of respond_with. The way it renders errors is like this:

# /app/controllers/articles_controller.rb
def create
  article = Article.new(params[:article])
  article.save
  respond_with(article)
end

Response:

{
  errors: {
    title: ["can't be blank", "must be longer than 10 characters"],
    body: ["can't be blank"]
  }
}

I would like to have it respond in a different way. Is there any way to override this format?

I've successfully done this by monkey patching the ActionController::Responder class and redefining json_resource_errors but this seems like a bad way to do this.

2

There are 2 best solutions below

0
On

The easiest way would be to not use respond_with but respond_to (docs).

respond_to do |format|
  format.json { article.valid? ? article.to_json : article.custom_json_errors }
end
0
On

AFAIK, the correct way is to customize json_resource_errors inside e.g. your application_responder.rb

for example like this:

class ApplicationResponder < ActionController::Responder
  include Responders::FlashResponder
  include Responders::HttpCacheResponder

  # Redirects resources to the collection path (index action) instead
  # of the resource path (show action) for POST/PUT/DELETE requests.
  include Responders::CollectionResponder

  def json_resource_errors
    { errors: resource.errors }
  end
end