I have addresses & phones associations against the user model which means that a user can have multiple addresses and multiple phones.
I have to store 1 address and 1 phone at the time of signup where I am using devise_token_auth gem.
user.rb
has_many :addresses, dependent: :destroy
has_many :phones, dependent: :destroy
accepts_nested_attributes_for :addresses
accepts_nested_attributes_for :phones
application_controller.rb
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up,
keys: [
:email,
:name,
addresses_attributes: %i[street_1 street_2 city state country zip label default],
phones_attributes: %i[label dial default]
]
)
end
Problem
If I send the address and phone attributes empty/invalid, I am receiving the error JSON as follows:
{
"status": "error",
"data": {
...
},
"errors": {
"addresses.label": [
"can't be blank"
],
"addresses.street_1": [
"can't be blank"
],
"addresses.city": [
"can't be blank"
],
"phones.dial": [
"Not a valid 10-digit telephone number"
],
"full_messages": [
"Addresses label can't be blank",
"Addresses street 1 can't be blank",
"Addresses city can't be blank",
"Phones dial Not a valid 10-digit telephone number",
]
}
}
Following the article Errors can be indexed with nested attributes in Rails 5 by using index_errors: true
, I am receiving the error JSON as:
{
"status": "error",
"data": {
...
},
"errors": {
"addresses[0].label": [
"can't be blank"
],
"addresses[0].street_1": [
"can't be blank"
],
"addresses[0].city": [
"can't be blank"
],
"phones[0].dial": [
"Not a valid 10-digit telephone number"
],
"full_messages": [
"Addresses[0] label can't be blank",
"Addresses[0] street 1 can't be blank",
"Addresses[0] city can't be blank",
"Phones[0] dial Not a valid 10-digit telephone number",
]
}
}
What I really need is something like following which I can easily traverse in any language:
errors: {
addresses: {
label: ["can't be blank"],
street_1: ["can't be blank"],
...
},
phones: {
dial: ["Not a valid 10-digit telephone number"]
}
}