我想自定义respond_with
的错误响应。它呈现错误的方式如下:
# /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"]
}
}
我想让它以不同的方式回应。有没有办法覆盖这种格式?
我通过猴子修补ActionController :: Responder类并重新定义json_resource_errors
来成功完成此操作,但这似乎是一种不好的方法。
答案 0 :(得分:1)
最简单的方法是不使用respond_with
,而respond_to
(docs)。
respond_to do |format|
format.json { article.valid? ? article.to_json : article.custom_json_errors }
end
答案 1 :(得分:0)
AFAIK,正确的方法是在内部定制json_resource_errors,例如你的application_responder.rb
例如:
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