Pundit 从另一个角色继承
Pundit inheritance from another role
我有一个 Rails 项目使用 Devise 和非常棒的 Pundit Gem。我使用三种不同的角色 - 超级管理员、管理员和用户。
我想知道是否有可能以某种方式定义超级管理员拥有管理员拥有的所有权利以及更多权利。这样我的观点就不用再写<% if current_user.admin? || current_user.superadmin? %>
了。
您在视图中使用 if current_user.admin? || current_user.superadmin?
的事实是一种特别臭的代码味道,表明您没有正确使用授权层。
您应该使用:
<% if policy(@post).update? %>
<%= link_to "Edit post", edit_post_path(@post) %>
<% end %>
并在您的策略中定义规则 - 不要到处散布授权逻辑(谁可以做什么)。
class ApplicationPolicy
# ...
def update?
admin?
end
private
def admin?
user.admin? || user.superadmin?
end
end
class PostPolicy < ApplicationPolicy
def update?
super || record.author == user
end
end
如果您使用像 Rolify 这样的角色库,您还可以通过为超级管理员提供管理员和超级管理员角色来简化此操作:
@user.add_role(:admin)
@user.add_role(:superadmin)
@user.has_role?(:admin) # true
我有一个 Rails 项目使用 Devise 和非常棒的 Pundit Gem。我使用三种不同的角色 - 超级管理员、管理员和用户。
我想知道是否有可能以某种方式定义超级管理员拥有管理员拥有的所有权利以及更多权利。这样我的观点就不用再写<% if current_user.admin? || current_user.superadmin? %>
了。
您在视图中使用 if current_user.admin? || current_user.superadmin?
的事实是一种特别臭的代码味道,表明您没有正确使用授权层。
您应该使用:
<% if policy(@post).update? %>
<%= link_to "Edit post", edit_post_path(@post) %>
<% end %>
并在您的策略中定义规则 - 不要到处散布授权逻辑(谁可以做什么)。
class ApplicationPolicy
# ...
def update?
admin?
end
private
def admin?
user.admin? || user.superadmin?
end
end
class PostPolicy < ApplicationPolicy
def update?
super || record.author == user
end
end
如果您使用像 Rolify 这样的角色库,您还可以通过为超级管理员提供管理员和超级管理员角色来简化此操作:
@user.add_role(:admin)
@user.add_role(:superadmin)
@user.has_role?(:admin) # true