简体   繁体   中英

How to permit a new parameter in rails (devise) when implementing role based authorization

I'm working on creating an application with role based authorization.So,In i have created a migration to devise users to add a new column "role" And I have the following code block in my applications controller to permit the new parameter(role).But still when i try to sign up as a new user.I get the error that the parameter role is unpermitted.Please help me to solve this issue.

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
  devise_parameter_sanitizer.permit(:sign_up)  { |u| u.permit(  :email, :password, :password_confirmation, roles: [] ) }
end

end

This is what i've got in my user model

class User < ApplicationRecord
  belongs_to :role
  # has_many :Product
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

         ROLES = %i[admin manager customer]

def user_params
  params.require(:user).permit(:name, :email, :password, :password_confirmation, :role)
end


end

migration is as follows

class AddRoleToUsers < ActiveRecord::Migration[5.0]
  def change
    add_column :users, :role, :string
  end
end

Please help me to solve this issue.Thank you.

Your user model doesn't have access to params, so you can remove the user_params method from there. Unless you're nesting attributes, you won't need to pass in the array for the role attribute, so change

devise_parameter_sanitizer.permit(:sign_up)  { |u| u.permit(  :email, :password, :password_confirmation, roles: [] ) }

to

devise_parameter_sanitizer.permit(:sign_up)  { |u| u.permit(  :email, :password, :password_confirmation, :role ) }
#

And you should be good to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM