【发布时间】:2016-04-29 22:27:01
【问题描述】:
在我们现在拥有的 devise_for 模块中,我们至少有两个角色:admin 和 user。我的目标是在任何给定时间,只有一个管理员,并且只有管理员可以创建/删除其他用户。我已经关注了这个post,所以我必须登录并有权创建一个新用户,因为默认情况下sign_up 页面不需要权限。但是,现在管理员和用户之间没有区别,这意味着两个角色都可以创建其他角色,这不是我想要的功能。应该怎么做,只有管理员才能创建其他用户,即以用户身份访问/users/sign_up时,会弹出“权限不足?”这样的错误。
让我给你我现在拥有的东西:
app/policies/user_policy.rb:
class UserPolicy
attr_reader :current_user, :model
def initialize(current_user, model)
@current_user = current_user
@user = model
end
def index?
@current_user.admin?
end
def new?
@current_user.admin?
end
def show?
@current_user.admin? or @current_user == @user
end
def create?
@current_user.admin?
end
def update?
@current_user.admin?
end
def destroy?
return false if @current_user == @user
@current_user.admin?
end
end
app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
prepend_before_action :require_no_authentication, only: [:cancel]
prepend_before_action :authenticate_scope!, only: [:new, :create, :edit, :update, :destroy]
def new
super
end
end
config/routes.rb:
...
devise_for :users, :controllers => {:registrations => "registrations"}
resources :users
...
附:我试着看看我可以为原始代码 devise/registrations_controller.rb [link] 做些什么,但没有看到任何明显足以让我改变的东西......
【问题讨论】:
-
SO Link 提供了一个很好的例子来说明如何做到这一点。
标签: ruby-on-rails ruby devise