简体   繁体   English

Rails 5,设计嵌套属性,不允许的参数

[英]Rails 5, devise nested attributes, unpermitted parameters

I'm using Devise in my Ruby on Rails application. 我在Ruby on Rails应用程序中使用Devise。 When users signs up or updates their account I also want to create / update their AddressInformation . 当用户注册或更新其帐户时,我也想创建/更新其AddressInformation

class User < ApplicationRecord belongs_to :address_information accepts_nested_attributes_for :address_information, allow_destroy: true [...]

My _form.html.haml looks like this: 我的_form.html.haml看起来像这样:

= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f|
  = devise_error_messages!
  .form-group
    = f.label :name
    = f.text_field :name

  = f.fields_for :address_informations, resource.address_information do |address_field|
    .form-group
      = address_field.label :address
      = address_field.text_field :address
    .form-group
      = address_field.label :care_of
      = address_field.text_field :care_of
    .form-group
      = address_field.label :zip_code
      = address_field.text_field :zip_code
    .form-group
      = address_field.label :city
      = address_field.text_field :city

I have tried to add the attributes like this: 我试图添加这样的属性:

class Users::RegistrationsController < Devise::RegistrationsController
  before_action :configure_sign_up_params, only: [:create]
  before_action :configure_account_update_params, only: [:update]

  [...]

  # If you have extra params to permit, append them to the sanitizer.
  def configure_account_update_params
    devise_parameter_sanitizer.permit(:account_update, keys: [
      :name,
      address_information: [
        :address,
        :care_of,
        :zip_code,
        :country,
        :state
      ]
    ])
  end

When I try to update the user I get the following error: 当我尝试更新用户时,出现以下错误:

Unpermitted parameter: :address_informations
(0.2ms)  BEGIN
(0.2ms)  ROLLBACK

Any ideas on what I'm missing? 关于我所缺少的任何想法吗?

In your form definition, the resource name is in plural 在您的表单定义中,资源名称为复数形式

 = f.fields_for :address_informations, resource.address_information do |address_field|

since you are expecting attributes for :address_information you should change it to 由于您期望使用:address_information属性,因此应将其更改为

 = f.fields_for :address_information, resource.address_information do |address_field|

Also when working with strong parameters and nested attributes you should attach the _attributes suffix to the attributes name - address_information_attributes 同样,在使用强参数和嵌套属性时 ,应将_attributes后缀附加到属性名称address_information_attributes

  def configure_account_update_params
    devise_parameter_sanitizer.permit(:account_update, keys: [
      :name,
      address_information_attributes: [
        :address,
        :care_of,
        :zip_code,
        :country,
        :state
      ]
    ])
  end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM