Home > Software engineering >  Rails Devise, extra params don't work in RegistrationsController
Rails Devise, extra params don't work in RegistrationsController

Time:09-28

I'm having issues with adding usernames to the Devise controller. The error message I get in the console when creating a new user is: "Unpermitted parameter: :username."

However I'm following the docs on github which says I should add parameters like this:

In registrations_controller.rb (this don't work)

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

    protected

    #If you have extra params to permit, append them to the sanitizer.
    def configure_sign_up_params
        devise_parameter_sanitizer.permit(:sign_up, keys: [:username])
    end
    
    #If you have extra params to permit, append them to the sanitizer.
    def configure_account_update_params
        devise_parameter_sanitizer.permit(:account_update, keys: [:username])
    end
end

However doing this instead in the application control works:

class ApplicationController < ActionController::Base
    before_action :configure_permitted_parameters, if: :devise_controller?

    protected

    def configure_permitted_parameters
        added_attrs = [:username]
        devise_parameter_sanitizer.permit :sign_up, keys: added_attrs
        devise_parameter_sanitizer.permit :account_update, keys: added_attrs
    end
end

I don't understand how one works and the other don't.

CodePudding user response:

You need to configure the routes to use your custom controller

devise_for :users, controllers: { 
  # ...
  registrations: "users/registrations" 
}

You don't need to two seperate callbacks either since devise_parameter_sanitizer keeps different parameters lists for different actions anyways.

module Users
  class RegistrationsController < Devise::RegistrationsController
    before_action :configure_permitted_parameters

    protected
    def configure_permitted_parameters
        added_attrs = [:username]
        devise_parameter_sanitizer.permit :sign_up, keys: added_attrs
        devise_parameter_sanitizer.permit :account_update, keys: added_attrs
    end
  end
end
  • Related