简体   繁体   English

实施基于角色的授权时,如何在rails(设计)中允许新参数

[英]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. 我正在创建具有基于角色的授权的应用程序。因此,在我中,我创建了一个迁移以设计用户以添加新列“ role”,并且我的应用程序控制器中具有以下代码块以允许新参数(role) )。但是当我尝试注册为新用户时,仍然收到错误消息,指出参数角色不被允许。请帮助我解决此问题。

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. 您的用户模型无权访问params,因此您可以从那里删除user_params方法。 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. 而且您应该很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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