2

我有针对用户模型的地址和电话关联,这意味着用户可以有多个地址和多个电话。

在我使用 devise_token_auth gem 的注册时,我必须存储 1 个地址和 1 个电话。

用户.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

问题

如果我发送的地址和电话属性为空/无效,我将收到如下错误 JSON:

{
    "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",
        ]
    }
}

继文章Errors can be indexed with nested attributes in Rails 5 by usingindex_errors: true之后,我收到错误 JSON 为:

{
    "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",
        ]
    }
}

我真正需要的是以下内容,我可以轻松地用任何语言遍历:

errors: {
   addresses: {
      label: ["can't be blank"],
      street_1: ["can't be blank"],
      ...
   },
   phones: {
      dial: ["Not a valid 10-digit telephone number"]
   }
}
4

0 回答 0