Kevin van den Bekerom Kevin van den Bekerom - 3 years ago 141
Ruby Question

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.

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. Possible solution:

  1. Add status code to errors hash, e.g.
    errors.add(status_code: '409')
    . Then either render the status code from errors, or render 422 if multiple exists.

The problem with the above solution is that I do not know how to call the
function on a 'standard' validator.

My render code:

render json: model, status: :created
render json: model.errors, status: :unprocessable_entity

Which I would like to extent that it can render different status codes based on validation results.

Answer Source

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.errors.add(:base, "Duplicate names not allowed!")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download