4

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.

2
  • Why don't you instead of rendering a json, return head :conflict? Commented Jul 25, 2017 at 19:06
  • @MaximFedotov The job if this rest api server is purely handling rest calls. It does not need to render anything graphical, just some specified json structures ;) Commented Jul 26, 2017 at 8:28

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.