2016-02-18 10 views
0

我設置cancancan來實現此功能: 如果用戶是管理員,它可以銷燬除自己以外的每個用戶。 這是我ability.rb安裝cancancan用戶無法自行銷燬

class Ability 
    include CanCan::Ability 

    def initialize(user) 
    if user.role == 'admin' 
     cannot :destroy, User, id: user.id 
    end 
    end 
end 

這是我的看法

<h1>Listing Users</h1> 

<table> 
    <thead> 
    <tr> 
    <th>E-Mail</th> 
    <th>Name</th> 
    <th>Role</th> 
    <th colspan="3"></th> 
    </tr> 
    </thead> 

    <tbody> 
    <% @users.each do |user| %> 
     <tr> 
     <td><%= user.email %></td> 
     <td><%= user.name %></td> 
     <td><%= user.role %></td> 
     <% if can? :destroy, @user %> 
     <%= link_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' } %> 
     <% end %> 
     </tr> 
    <% end %> 
    </tbody> 
</table> 

即使在此設置有沒有現在每個用戶的最後破壞鏈接。我想要的是每個用戶背後都有一個銷燬鏈接,但管理員本身。我該怎麼辦?謝謝!

回答

0

你的主要問題是,你打電話if can? :destroy, @user@user不存在:

<% @users.each do |user| %> 
    <% if can? :destroy, user %> 
<% end %> 

如果原來的答案不工作,也許你會用更好block評估user對象:

#app/models/ability.rb 
class Ability 
    include CanCan::Ability 

    def initialize(user) 
    user ||= User.new 
    case user.role 
     when "admin" 
     cannot :destroy, User do |x| 
      x.id == user.id 
     end 
     end 
    end 
    end 
end 

這將允許您使用:

<%= link_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' } if can? :destroy, user %> 

...雖然修復第一個問題,我認爲,將解決您的問題。

+1

仍然不讓我刪除用戶 – DevArenaCN

0

只是因爲管理員不能銷燬自己,不會授予其銷燬其他用戶的權限。你可以嘗試給它銷燬權限。

class Ability 
    include CanCan::Ability 

    def initialize(user) 
    if user.role == 'admin' 
     cannot :destroy, User, id: user.id 
    else 
     can :destroy, User 
    end 
    end 
end 
+0

仍然一樣,沒有銷燬所有用戶信息旁邊的鏈接 – DevArenaCN