Validation error messages: add response code to default validators

I am looking for the best practice / solution for responding responses with different http-response codes than 422 - not processed object.

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 check failed. Possible Solution:

  • Add status code to error hash, eg. errors.add(status_code: '409')

    ... Then either get the status code out of errors or do 422 if multiple exist.

The problem with the above solution is that I don't know how to call the function errors.add

on a "standard" validator.

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 prove that it can display different status codes based on check results.

+3


source to share


1 answer


In this case, making a custom validator can be one approach and you can always extend 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

      

+1


source







All Articles