简体   繁体   English

Rails验证错误消息:将响应代码添加到默认验证器

[英]Rails validation error messages: Add response code to default validators

I am looking for a best-practise / solution to render responses with different http-response codes than 422 - unprocessable entity. 我正在寻找一个最佳实践/解决方案来呈现响应不同的http响应代码而不是422 - 不可处理的实体。

I have a simple validator: 我有一个简单的验证器:

validates :name, presence: true, uniqueness: {message: 'duplicate names are not allowed!'}

I want to return status code 409 - Conflict (:conflict) when this validation fails. 我想在此验证失败时返回状态代码409 - 冲突(:冲突)。 Possible solution: 可能的方法:

  1. Add status code to errors hash, eg errors.add(status_code: '409') . 将状态代码添加到错误哈希,例如errors.add(status_code: '409') Then either render the status code from errors, or render 422 if multiple exists. 然后从错误中呈现状态代码,或者如果存在多个则呈现422。

The problem with the above solution is that I do not know how to call the errors.add function on a 'standard' validator. 上述解决方案的问题是我不知道如何在'标准'验证器上调用errors.add函数。

My render code: 我的渲染代码:

if model.save
    render json: model, status: :created
  else
    render json: model.errors, status: :unprocessable_entity
  end

Which I would like to extent that it can render different status codes based on validation results. 我想扩展它可以根据验证结果呈现不同的状态代码。

In this case, creating a custom validator might be one approach and you could always expand the complexity 在这种情况下,创建自定义验证器可能是一种方法,您可以始终扩展复杂性

validates_with NameValidator

Custom validator 自定义验证器

class NameValidator < ActiveModel::Validator
  def validate(record)
    if record.blank? || Model.where(name: record.name).exists?
      record.errors.add(:base, "Duplicate names not allowed!")
    end
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM