0

我使用 Sorcery 和 Cancan 制作了一个简单的基于角色的身份验证,该数据库包含一个名为 ROLE 的列,在注册用户时可以是管理员或普通用户,

Relato 是一个脚手架,您可以在其中创建“报告”,我希望普通用户只能看到自己创建的那些,也可以做其他事情(更新、销毁)。

我的能力.rb

def initialize(user)

 if user.role == 'admin'
  can :manage, :all
 elsif user.role == 'normal'
   can :create, Relato
   can :manage, Relato, :user_id => user.id
   can [:read, :update, :destroy], User, :id => user.id

 end

无需控制保护

在我看来 index.html.erb 它列出了我放的所有“报告”

<% if can? :index, Relato %> 
<tbody>
<% @relatos.each do |relato| %>
  <tr class="alt">
    <td><%= relato.cliente.name %></td>  
     <td><%= relato.projeto.name %></td>  
      <td><%= relato.local_id %></td>  
      <td><%= relato.task_id %></td>  
      <td><%= relato.time %></td>  
     <td><%= relato.comment %></td>  
    <td><%= relato.isdoe %></td>  
       <td><%= link_to 'Editar', edit_relato_path(relato) %></td>  
      <td><%= link_to 'Deletar', relato, method: :delete, data: { confirm: 'Are you sure?' } %>
    </tr>
   <% end %>
<% end %>

但它不起作用,用户看不到他的报告,使用管理员帐户一切都很好。

4

2 回答 2

0

由于您有 的集合@relatos,因此您不应依赖 的实例Relato来检查该功能。

考虑使用类似can?(:index, Relato). 请注意,我正在使用该类。

现在您可以设置该功能,但是由于正在使用该类,因此您无法检查检查属性,例如user_id.

由于您拥有can :manage, :all管理员权限,因此他们应该能够阅读@relatos.

让我知道您是否想实现其他目标。

于 2015-06-23T20:40:32.257 回答
0
<% if can? :read, Relato %> 

不是@Relatio

此外,您可能需要考虑使用级联功能。简单地说,管理员拥有普通用户的所有能力。此外,他还获得了一些特殊的管理能力。为了说明为什么这是一个好主意,想象一下如果意识到您还需要一个编辑角色:

def initialize(user)
  if user.role == 'admin'
    can :manage, :all
  elsif user.role == 'normal'
    can :create, Relato
    can :manage, Relato, :user_id => user.id
    can [:show, :update, :destroy], User, :id => user.id
  elsif user.role == 'editor'
    can :manage, Relato 
    can [:show, :update, :destroy], User, :id => user.id
  end
end

那是很多重复。反而:

def initialize(user)

  # Anybody can change their profile
  can [:show, :update, :destroy], User, :id => user.id

  # Anybody can edit Relatos they own.
  can :manage, Relato, :user_id => user.id

  if user.role == 'admin'
    can :manage, :all
  end

  if user.role == 'editor'
    can :manage, Relato
  end
end
于 2015-06-23T20:44:51.933 回答