【问题标题】:How to customize the JSON that respond_with renders in case of validation errors?如果出现验证错误,如何自定义 response_with 呈现的 JSON?
【发布时间】:2017-06-12 15:52:19
【问题描述】:

在控制器中,我想将if..render..else..render 替换为respond_with

# Current implementation (unwanted)
def create
  @product = Product.create(product_params)
  if @product.errors.empty?
    render json: @product
  else
    render json: { message: @product.errors.full_messages.to_sentence }
  end
end

# Desired implementation (wanted!)
def create
  @product = Product.create(product_params)
  respond_with(@product)
end

respond_with 的问题在于,如果出现验证错误,JSON 会以不符合客户端应用程序期望的特定方式呈现:

# What the client application expects:
{
  "message": "Price must be greater than 0 and name can't be blank"
}

# What respond_with delivers (unwanted):
{
  "errors": {
    "price": [
      "must be greater than 0"
    ],
    "name": [
      "can't be blank"
    ]
  }
}

产品、价格和名称是示例。我希望整个应用程序都有这种行为。

我正在使用responders gem,并且我已阅读可以自定义响应者和serializers。但是这些部分是如何组合在一起的呢?

如何自定义respond_with在出现验证错误时呈现的JSON?

【问题讨论】:

    标签: ruby-on-rails json active-model-serializers respond-with responders


    【解决方案1】:

    自定义用户警报的其他几种方法

    你可以把它排成一行:

    render json: { message: "Price must be greater than 0" }

    或者:您可以只引用您的 [locale file] 并在那里输入自定义消息。 1:

    t(:message)

    希望这会有所帮助:)

    【讨论】:

    • 感谢您的回答。实际上,这是我当前的实现。但我真正想要的是使用像respond_with(@product) 这样的响应器并自定义错误响应的错误布局。
    • 你试过放入变量吗?错误消息中没有出现“价格”一词的问题吗?
    • 问题不在于“价格”这个词没有出现。问题是我应该在控制器中使用respond_with(而不是render json:),并且在出现验证错误的情况下,呈现一个包含message 节点的JSON,并将所有完整的错误消息连接为一个句子 - - 同样,在控制器中使用respond_with,而不是render json:
    【解决方案2】:

    我找到了一种将错误哈希作为单个句子获取的临时方法。但它不仅是骇人听闻的,而且它也不能 100% 匹配所需的输出。我仍然希望有一种方法可以使用自定义序列化程序或响应程序来做到这一点。

    module ActiveModel
      class Errors
        def as_json(*args)
          full_messages.to_sentence
        end
      end
    end
    
    # OUTPUT
    {
      "errors": "Price must be greater than 0 and name can't be blank"
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-02
      • 1970-01-01
      • 1970-01-01
      • 2010-12-30
      • 2011-09-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多