我是ruby的新手,我正在研究一个错误结构,作为对我的api的响应。目前,验证错误返回如下:
{
"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"
]
}
}
,但我想要这样的:
{
"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"
}
}
我的模型:
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?
控制器:
# 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
您可以覆盖默认的活动记录翻译:
---
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
您可以在这里的文档中获得更深入的信息: https://guides.rubyonrails.org/i18n.html error-message-scopes