Home > Back-end >  How do I handle validation errors in ruby on rails 6
How do I handle validation errors in ruby on rails 6

Time:10-20

I am new to ruby and I am working on an error structure to be sent as response to my api. Currently, validation errors are returned like:

{
"status": 400,
"message": "Profile update was unsuccessfull",
"errors": {
    "first_name": [
        "is too short (minimum is 3 characters)"
    ],
    "phone_number": [
        "Enter a valid us phone number"
    ]
}

}

but I want something like:

{
"status": 400,
"message": "Profile update was unsuccessfull",
"errors": {
    "first_name": "firstname "is too short (minimum is 3 characters)",
    "phone_number": "Enter a valid us phone number"
}

}

My model:

validates :first_name, :last_name, :state, :referral_method, presence: true, length: { minimum: 3, maximum: 25 }
validates :phone_number, format: { with: VALID_PHONE_REGEX, message: "Enter a valid us phone number" }, if: :phone_number_changed?

Controller:

# Handle validation errors
rescue_from ActiveRecord::RecordInvalid do |exception|
 messages = exception.record.errors.messages
 messages.map {|k,v| messages[k]=v[0] }
 @response = { status: Status.bad_request, message: Message.profile_not_updated, 
 errors:messages}
 json_response(@response, :bad_request)
end

CodePudding user response:

You could overwrite default active record translations: 

---
en:
  activerecord:
    errors:
      models:
        user:
          attributes:
            first_name:
              too_short: First name is too short (minimum is 3 characters)
            phone_number:
              too_short: Enter a valid us phone number

You can have a deeper in the documentation here:  https://guides.rubyonrails.org/i18n.html#error-message-scopes

  • Related