覆盖respond_with的JSON响应以查找错误

时间:2015-08-03 21:14:50

标签: ruby-on-rails responders

我想自定义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来成功完成此操作,但这似乎是一种不好的方法。

2 个答案:

答案 0 :(得分:1)

最简单的方法是不使用respond_with,而respond_todocs)。

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