Anders
Anders

Reputation: 2941

Rails 5, devise nested attributes, unpermitted parameters

I'm using Devise in my Ruby on Rails application. When users signs up or updates their account I also want to create / update their 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_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?

Upvotes: 2

Views: 1459

Answers (1)

Vane Trajkov
Vane Trajkov

Reputation: 768

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

 = 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

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

Upvotes: 4

Related Questions