Ruby on rails 设置cancancan,用户无法';不要自毁
我正在设置cancancan以实现此功能: 如果用户是管理员,它可以销毁除他自己以外的所有用户。 这是我的能力Ruby on rails 设置cancancan,用户无法';不要自毁,ruby-on-rails,cancancan,Ruby On Rails,Cancancan,我正在设置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</
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>
列出用户
电子邮件
名称
角色
即使使用这种设置,现在在每个用户的末尾也没有销毁链接。我想要的是,除了管理员自己,每个用户背后都有一个销毁链接。我该怎么办?谢谢 仅仅因为管理员不能销毁自己,就不会授予管理员销毁其他用户的权限。您可以尝试授予它销毁权限
类能力
包括CanCan::能力
def初始化(用户)
如果user.role==“admin”
无法:销毁,用户,id:User.id
其他的
可以:销毁,用户
结束
结束
结束
您的主要问题是,如果可以,您正在呼叫:销毁,@user
当@user
不存在时:
<% @users.each do |user| %>
<% if can? :destroy, user %>
<% end %>
这将允许您使用:
<%= link_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' } if can? :destroy, user %>
。。。尽管修复了第一个问题,我认为可以解决您的问题。仍然一样,所有用户信息旁边没有销毁链接仍然不允许我删除该用户
<%= link_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' } if can? :destroy, user %>