Rails 5,设计嵌套属性,未经许可的参数

时间:2017-12-28 20:04:46

标签: ruby-on-rails ruby devise ruby-on-rails-5

我在Ruby on Rails应用程序中使用Devise。当用户注册或更新其帐户时,我还想创建/更新他们的AddressInformation

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

我的_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

我试图添加如下属性:

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

当我尝试更新用户时,出现以下错误:

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

关于我缺少的任何想法?

1 个答案:

答案 0 :(得分:3)

在表单定义中,资源名称为复数

newFashion()

因为您期望 = f.fields_for :address_informations, resource.address_information do |address_field| 的属性,所以应将其更改为

:address_information

使用strong parameters and nested attributes时,您应将 = f.fields_for :address_information, resource.address_information do |address_field| 后缀附加到属性名称 - _attributes

address_information_attributes