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

html - How to set bootstrap input responsive width? -

javascript - Highchart x and y axes data from json -

javascript - Get js console.log as python variable in QWebView pyqt -