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

时间:2017-07-26 07:13:51

标签: ruby-on-rails ruby-on-rails-4 cancan cancancan

我想在我的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 代码似乎没有问题&#34;每个用户一个角色&#34; 但是没有显示数据。请帮我解决这个问题。

2 个答案:

答案 0 :(得分: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的更新版本,仍由社区维护。

答案 1 :(得分:0)

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