Kevin van den Bekerom
Kevin van den Bekerom

Reputation: 137

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 errors.add function 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 extent that it can render different status codes based on validation results.

Upvotes: 4

Views: 2233

Answers (1)

Maxim Fedotov
Maxim Fedotov

Reputation: 1357

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

Upvotes: 2

Related Questions