繁体   English   中英

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

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

我正在创建具有基于角色的授权的应用程序。因此,在我中,我创建了一个迁移以设计用户以添加新列“ 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

这就是我在用户模型中得到的

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

迁移如下

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

请帮我解决这个问题。谢谢。

您的用户模型无权访问params,因此您可以从那里删除user_params方法。 除非您要嵌套属性,否则无需为角色属性传递数组,因此请进行更改

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

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

而且您应该很好。

暂无
暂无

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

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