我正在学习Michael的Rails教程。我已经到了第九章,有些代码我不明白。请参见下面的第4行,为什么我们需要在current_user?(user)
前面使用一个current_user?(user)
来使其成为!current_user?(user)
--我们不需要true && true
来传递if语句,以便Admin可以看到删除操作。
如果用户登录并是管理员,则current_user.admin? == true
、current_user?(user) = true
和!current_user?(user)
将为false,If语句不会通过。
_user.html.erb
<li>
<%= gravatar_for user, size: 52 %>
<%= link_to user.name, user %>
<% if current_user.admin? && !current_user?(user) %>
| <%= link_to "delete", user, method: :delete,data: { confirm: "You sure?" } %>
<% end %>
</li>
sessions_helper.rb
def current_user=(user)
@current_user = user
end
def current_user
remember_token = User.encrypt(cookies[:remember_token])
@current_user ||= User.find_by(remember_token: remember_token)
end
def current_user?(user)
user == current_user
end
预先谢谢.
发布于 2013-11-27 04:50:25
只有管理员才能删除用户,而不能删除自己。
来自railstutorial.org第9.4章:
管理用户应该看到这样的链接,通过单击delete链接,我们期望管理员删除用户。
和
还请注意,我们添加了一个测试,以验证管理员没有看到要删除自己的链接。
所以:
current_user.admin?
的意思是“当前用户是管理员吗?”
!current_user?(user)
的意思是“当前用户与我显示的用户不同吗?”
总之,<% if current_user.admin? && !current_user?(user) %>
作为显示Delete
链接的测试,意味着删除链接只显示给管理员,而不显示他们自己的user
详细信息。也就是说,只有管理员才能删除用户,而不能删除自己。
请记住,用户视图显示的是用户列表,而不仅仅是当前用户。在这个上下文中,user
是指视图当时显示的用户模型。
检查这幅图像,注意Example User
没有删除链接,但其他人都有。
https://stackoverflow.com/questions/20234075
复制相似问题