首页 文章

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

提问于
浏览
0

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

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

经理可以访问产品,交付

客户可以访问服务

我写了如下能力模型 .

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%>

但即使我以管理员身份登录,也不会显示数据 . 我指的是以下cancan文档 . https://github.com/CanCanCommunity/cancancan/wiki/Role-Based-Authorization代码似乎没有"One role per user"但是数据没有显示 . 请帮我解决这个问题 .

2 回答

  • 1

    我不是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

    它是CanCan的更新版本,仍由社区维护 .

  • 0

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

相关问题