Rails 5,设计嵌套属性,未经许可的参数
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
关于我缺少的任何想法?
答案
在表单定义中,资源名称为复数形式
= f.fields_for :address_informations, resource.address_information do |address_field|
因为你期望:address_information
的属性你应该改为
= f.fields_for :address_information, resource.address_information do |address_field|
在使用strong parameters and nested 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
以上是关于Rails 5,设计嵌套属性,未经许可的参数的主要内容,如果未能解决你的问题,请参考以下文章
如何仅更新 rails 6 中 current_user 的嵌套表单属性?