Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何限制rails(cancan gem)中不同用户角色对模型的访问?_Ruby On Rails_Ruby_Devise_Cancan - Fatal编程技术网

Ruby on rails 如何限制rails(cancan gem)中不同用户角色对模型的访问?

Ruby on rails 如何限制rails(cancan gem)中不同用户角色对模型的访问?,ruby-on-rails,ruby,devise,cancan,Ruby On Rails,Ruby,Devise,Cancan,在我的rails应用程序中,我需要3个用户级别,分别为管理员、经理、客户。 因此,我创建了3个设计模型,分别为管理员、经理和客户。 在我的应用程序中,有用于产品、交付和服务的模型和控制器。 我想设置每个模型的访问级别 所以管理员可以访问所有模型和控制器 经理有权访问产品、交付 客户有权获得服务 如何编写与这些需求相匹配的能力模型 我写的如下,不知道是否正确 class Ability include CanCan::Ability def initialize(user)

在我的rails应用程序中,我需要3个用户级别,分别为管理员、经理、客户。 因此,我创建了3个设计模型,分别为管理员、经理和客户。 在我的应用程序中,有用于产品、交付和服务的模型和控制器。 我想设置每个模型的访问级别

所以管理员可以访问所有模型和控制器 经理有权访问产品、交付 客户有权获得服务 如何编写与这些需求相匹配的能力模型 我写的如下,不知道是否正确

class Ability
  include CanCan::Ability
    def initialize(user)
        # Define abilities for the passed in user here. For example:
        #
          user ||= User.new # guest user (not logged in)
          if user.admin?
            can :manage, :all
          elsif user.manager?
            can :manage, product ,delivery
          elsif user.customer?
            can :manage, services
          end
    end
请帮助我为模型编写代码,以限制不同的用户角色访问。
请帮助我吧

我认为解决这个问题的最简单方法是使用控制器。假设您有一个带有控制器的图书模型,并且只希望允许管理员访问此部分。最好在bookings控制器中创建一个方法,并使用before action方法调用它:

class BookingsController < ApplicationController
  before_action :check_admin

  def check_admin
    return unless admin_signed_in?
    redirect_to root_path, error: 'You are not allowed to access this part of the site'
  end
end
将只在这些控制器操作之前执行检查,并允许任何人访问索引和显示操作

before_action :check_admin, only: [:edit, :create, :delete, :update, :new]