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

后端 未结 3 1826
孤城傲影
孤城傲影 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条回答
  •  旧时难觅i
    2021-02-05 17:09

    Rails 5+ or Rails 4 and active_model-errors_details gem:

    class User
      include ActiveModel::Model
      validate :forbid_special_email
      attr_accessor :email
    
      private
    
      def forbid_special_email
        errors.add(:email, 'is forbidden', code: 1234) if email == 'john@example.com'
      end
    end
    
    user = User.new(email: 'john@example.com')
    user.validate
    user.errors.full_messages # ["Email is forbidden"]
    user.errors.details # {:email=>[{:error=>"is forbidden", :code=>1234}]}
    

提交回复
热议问题