如何在 respond_with 在验证错误时自定义渲染的 JSON?

5
在控制器中,我想用respond_with替换if..render..else..render:
# 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,我已经阅读了可以自定义responders和serializers的资料。但这些组件如何配合使用呢?

如何定制respond_with在验证错误时呈现的JSON?

2个回答

3

自定义用户警报的另外两种方式:

你可以直接在行内写入:

render json: { message: "价格必须大于0" }

或者:你可以引用你的 [本地化文件] 并在其中放置自定义消息。 1:

t(:message)

希望这有所帮助 :)


谢谢你的回答。实际上,这就是我的当前实现方式。但我真正想要的是使用像respond_with(@product)这样的响应器,并为错误响应自定义错误布局。 - João Souza
你尝试过放入一个变量吗?问题是“Price”这个词在错误信息中没有出现吗? - gwalshington
问题不在于“Price”这个词没有出现。问题在于我需要在控制器中使用respond_with(而不是render json:),并且在验证错误的情况下,渲染一个包含“message”节点的JSON,其中所有完整的错误消息都被连接成一个句子 - 同样,在控制器中使用respond_with,而不是render json: - João Souza

0

我找到了一个临时的方法来将错误哈希作为单个句子获取。但是这不仅是hackish,而且也不能完全匹配所需的输出。我仍然希望有一种使用自定义序列化器或响应器来完成此操作的方法。

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"
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接