【问题标题】:Overriding the JSON response of respond_with for errors覆盖respond_with的JSON响应以获取错误
【发布时间】:2015-08-03 21:14:50
【问题描述】:

我想自定义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 成功地做到了这一点,但这似乎是一个不好的方法。

【问题讨论】:

    标签: ruby-on-rails responders


    【解决方案1】:

    最简单的方法是不使用respond_with,而是使用respond_to (docs)。

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

    【讨论】:

      【解决方案2】:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-25
        • 1970-01-01
        • 1970-01-01
        • 2015-01-12
        • 1970-01-01
        • 2016-06-02
        • 1970-01-01
        相关资源
        最近更新 更多