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

activerecord, error-code, ruby-on-rails, validation

Solution

`errors` is just a plain hash, with the key represents the attribute which has an error, and the value represents the error message. So technically your requirement is doable by replacing the text message with a hash. But the downside is you may need to do more things to show the errors in new format.

For example, use a custom validator to add error code

class Foo < ActiveRecord::Base
  attr_accessible :msiisnd
  validate :msiisdn_can_not_be_blank

  def msiisdn_can_not_be_blank
    if msiisdn.blank?
      errors.add(:msiisdn, {code: 101, message: "cannot be blank"})
    end
  end
end

Then use it

foo = Foo.new
foo.errors.count
#=> 0
foo.valid?
#=> false
foo.errors.count
#=> 1
foo.errors[:msiisdn]
#=> [{ code: 101, message: "can not be blank"}]
foo.errors[:msiisdn][0][:code]
#=> 101

So you can use it. But you need to do more work when you need to show the errors correctly, say displaying errors in a form, as this is not a convention.

Problem

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 returned in addition to error message, for example, we have a Bill model, which has a msisdn attribute, if msisdn is null, the error code is 101, if the msisdn doesn't complaint with MSISDN format, the error code is 102, when the client submits a request through REST interface, and if the validation fails, we should return a json object like ``` bill: { error_code: 101, error_message: "msisdn can't be null" } ``` Is there a way to tell activerecord to generate an error code in addition to error messages? Thanks a lot.

Original source