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
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}]}