无法自动加载常量角色,需要 role.rb 在 rails cancan 基于角色的授权中定义它

Unable to autoload constant Role,expected role.rb to define it issue in rails cancan role based authorization

我正在开发一个 rails 应用程序,在 cancan 文档的帮助下具有基于角色的用户授权。 https://github.com/ryanb/cancan/wiki/Role-Based-Authorization 在我的 rails 应用程序中,我想要 3 个用户级别,如 Admin、Manager、Customer。因此,我创建了一个作为用户的设计模型,并添加了一个迁移以在用户注册时将用户角色添加到 it.So,它存储用户角色(无论他是管理员、经理还是客户)。在我的应用程序中,有用于产品、交付和服务的模型和控制器。我想为每个模型设置访问级别。

所以管理员可以访问所有模型、控制器

经理有权访问产品、交付

客户可以访问服务

而我写的能力模型如下

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

用户模型如下

class User < ApplicationRecord
  belongs_to :role
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

         ROLES = %i[admin manager customer]

end

榜样

class ApplicationController < ActionController::Base

end

尝试访问产品控制器显示视图时出现以下错误。

LoadError in ProductsController#show
Unable to autoload constant Role, expected /Users/tharindu/MyTasks/try2/mynewtask/app/models/role.rb to define it

Extracted source (around line #7):
5
6
7
8
9
10

    user ||= User.new # guest user (not logged in)

       if user.role == "admin"
         can :manage, :all, @products
       elsif user.role == "manager"
         can :read, Products, Delivery,Accounts

请帮我解决这个问题

您的榜样没有定义角色 class。变化

class ApplicationController < ActionController::Base

class Role < ApplicationRecord

您尝试实施的教程没有单独的 Role 模型,您正在添加关联 belongs_to :role。相反,您将 role 保存在 User table 本身中。因此,删除应该解决问题的定义的关联。

目前 User 会有一个 role 您也可以使用 bitmask.

为他分配多个角色,如教程中所述

但是使用这两种方法中的任何一种都不会创建单独的模型,因此无法定义关联,而您需要创建实例方法。对于单独的 Role 模型,请参考:https://github.com/ryanb/cancan/wiki/Separate-Role-Model