1

我想自定义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但这似乎是一种不好的方法。

4

2 回答 2

1

最简单的方法是不使用respond_withbut respond_to( docs )。

respond_to do |format|
  format.json { article.valid? ? article.to_json : article.custom_json_errors }
end
于 2015-08-03T21:32:18.927 回答
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
于 2017-08-15T09:40:48.947 回答