簡體   English   中英

Rails 5,設計嵌套屬性,不允許的參數

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

我在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|

同樣,在使用強參數和嵌套屬性時 ,應將_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