ruby - Rails validation error messages: Add response code to default validators -


i looking best-practise / solution render responses different http-response codes 422 - unprocessable entity.

i have simple validator:

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

i want return status code 409 - conflict (:conflict) when validation fails. possible solution:

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

the problem above solution not know how call errors.add function on 'standard' validator.

my render code:

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

which extent can render different status codes based on validation results.

in case, creating custom validator might 1 approach , expand 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 

Comments

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -