CanCan:只有管理员可以删除用户,但他不应该删除自己

时间:2013-08-14 07:53:31

标签: ruby-on-rails ruby-on-rails-3 cancan

def initialize(user)
 if user.has_role? :admin
  can :manage, :all
  can :destroy, User
  can [:update , :destroy], [Article, Comment]
 else
  can :read, :all
 end

如何只管理删除用户但无法删除自己?

我正在使用wice_grid gem,我已将此添加到我的视图中,但仍然可以删除自己

g.column do |user|
 if can? :destroy, @user && !current_user(user)
  link_to('Delete', user, method: :delete, data: { confirm: 'You sure?' })
 end
end

3 个答案:

答案 0 :(得分:3)

def initialize(user)
  if user.has_role? :admin
    can :manage, :all
    cannot :destroy, User, id: user.id 
  else
    can :read, :all
 end

g.column do |user|
  if can? :destroy, user
    link_to('Delete', user, method: :delete, data: { confirm: 'You sure?' })
  end
end

答案 1 :(得分:1)

为此请阅读Ability-Precedence,顺便说一句,你可以这样做:

if user.admin?
      can :manage, :all
      cannot :destroy, User, :id => current_user.id
end

由于

答案 2 :(得分:0)

试试这个

def initialize(user)
 if user.has_role? :admin
  can :read, :all
  can [:update, :destroy], [Article, Comment, User]
  cannot :destroy, User, id: user.id # it means do not destroy own-self(the id of object to be deleted is not equal to admin's id)
 else
  can :read, :all
 end

不要写'manage:all',好像找到它一样,控制永远不会停止,意味着其余的代码永远不会执行,因为'manage:all'意味着可以做所有事情,另一方面如果你指定比如'can [:update,:destroy],[Article,Comment,User]',它会适用于你的情况。