为什么输出未通过基于角色的授权(每个用户一个角色)中的能力检查



我希望在我的轨道应用程序中有 3 个用户级别作为管理员、经理、客户。因此,我创建了一个设计模型作为用户,并添加了一个迁移以向其添加用户角色。因此,当用户注册时,它会存储用户角色(无论他是管理员,经理还是客户(。在我的应用程序中,有用于产品,交付,服务的模型和控制器。我想为每个模型设置访问级别。

因此,管理员可以访问所有模型,控制器

经理有权访问产品、交付

客户有权访问服务

我编写了如下能力模型。

class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.roles == "admin"
can :manage , :all
elsif user.roles == "manager"
can :read, Products, Delivery
elsif user.roles == "customer"
can :read, Services
end
end
end

我对产品的显示视图如下。

<% if can? :manage ,@products%>
<h1>Products</h1>
<% @products.each do |product| %>
<p>     <%= product.name%>
<p>         <%= product.price %><br>
<p>    <%= product.qty %><br>
<%end%>
<%end%>

但即使我以管理员身份登录,数据也不会显示。 我指的是以下康康文档。 https://github.com/CanCanCommunity/cancancan/wiki/Role-Based-Authorization 代码似乎可以"每个用户一个角色" 但不显示数据。请帮我解决这个问题。

我不是CanCan的真正专家,但你可以试试:

class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
cannot :manage, :all # we can do this since the abilities are OR'ed
if user.roles.include?('admin')
can :manage , :all
elsif user.roles.include?('manager')
can :read, Products, Delivery
elsif user.roles.include?('customer')
can :read, Services
end
end
end

此外,如果是项目启动,请考虑CanCanCan。 https://github.com/CanCanCommunity/cancancan

它是CanCanCan的更新版本,仍由社区维护。

所有代码都是正确的,但问题出在强参数上。因此,当注册时,"角色"尚未保存在数据库中。因此,当检查能力时,不会传递用户查看内容,因为他们不是管理员,经理或客户

最新更新