我有一个带有用户模型的 Rails 应用程序,它可以有多个角色。我使用这样的位掩码实现了这一点:
class User < ActiveRecord::Base
DEFAULT_ROLES = %w[developer entrepreneur]
ROLES = ['admin', 'entrepreneur', 'developer']
def has_role?(role)
roles.include?(role.to_s)
end
def is?(role)
has_role?(role)
end
def roles=(roles)
self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.inject(0, :+)
end
def roles
ROLES.reject do |r|
((roles_mask.to_i || 0) & 2**ROLES.index(r)).zero?
end
end
end
在应用程序的注册页面中,我希望用户选择他们是“企业家”还是“开发人员”。但是,我想确保他们不能为自己(或其他任何人)分配任何其他角色,除非他们已经是管理员。
我的第一个想法是roles=
通过将其更改为看起来像的方法来执行此操作
def roles=(roles)
unless current_user.is?(:admin)
validates_inclusion_of roles, :in => DEFAULT_ROLES
end
self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.inject(0, :+)
end
但是,正如我发现的那样,您无法current_user
从模型内部访问(如果您考虑一下,我想这是有道理的......)
我的下一个尝试是看看我是否可以使用Strong Parameters来做到这一点。
我期待它看起来像这样(我正在使用设计,覆盖 RegistrationsController)
class RegistrationsController < Devise::RegistrationsController
private
def sign_up_params
if (user_signed_in?) && (current_user.is?(:admin))
params.require(:user).permit(:name, :school, :email, :password, :password_confirmation, {roles: User::ROLES})
else
params.require(:user).permit(:name, :school, :email, :password, :password_confirmation, {roles: User::DEFAULT_ROLES})
end
end
def account_update_params
if (user_signed_in?) && (current_user.is?(:admin))
params.require(:user).permit(:name, :school, :email, :password, :password_confirmation, :current_password, :about_me, {roles: User::ROLES})
else
params.require(:user).permit(:name, :school, :email, :password, :password_confirmation, :current_password)
end
end
end
然而,当我尝试这样做时,我得到了这个:
这让我觉得我误解了强参数的真正工作原理。
是否可以根据具有强参数的用户角色来限制用户可以为任何给定字段输入的值?如果没有,是否有不同的方法来实现这一点?