Ruby on rails 为错误重写respond_的JSON响应
我想用自定义Ruby on rails 为错误重写respond_的JSON响应,ruby-on-rails,responders,Ruby On Rails,Responders,我想用自定义respond\u的错误响应。它呈现错误的方式如下所示: # /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
respond\u的错误响应。它呈现错误的方式如下所示:
# /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"]
}
}
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
我想让它以不同的方式回应。有没有办法覆盖这种格式
我已经成功地做到了这一点,通过猴子修补ActionController::Responder类并重新定义json\u resource\u错误
,但这似乎是一种不好的方法 最简单的方法是不要使用respond\u with
,而是使用respond\u to
()
好的,正确的方法是自定义json_资源_错误,例如您的应用程序_responder.rb
例如:
# /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"]
}
}
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
class ApplicationResponder