Is there a way to return error code in addition to error message in rails active record validation?

后端 未结 3 1866
孤城傲影
孤城傲影 2021-02-05 16:04

In rails activerecord validation, normally if a validation fails, it will add an error message in the errors attribute of models, however our clients demands an error code be re

3条回答
  •  半阙折子戏
    2021-02-05 17:02

    Rails 5 will include a similar feature with foo.errors.details. You can easily use this to build better api errors.

    class Person < ActiveRecord::Base
     validates :name, presence: true
    end
    
    person = Person.new
    person.valid?
    person.errors.details
    # => {name: [{error: :blank}]}
    

    If you prefer code errors as numbers, you can easily match numbers with the error keys.

    For Rails 3 & 4 you can use this gem https://github.com/cowbell/active_model-errors_details witch is the exact same feature backported.

提交回复
热议问题