CanCan:用户无法查看自己的内容

时间:2015-06-23 20:15:26

标签: ruby-on-rails ruby cancan sorcery

我使用Sorcery和Cancan创建了一个基于auth的简单角色,该数据库包含一个名为ROLE的列,当注册用户时可以是admin或normal,

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

但它不起作用,用户无法看到他的报告,使用admin帐户一切都很好。

2 个答案:

答案 0 :(得分:0)

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

考虑使用can?(:index, Relato)之类的内容。请注意我正在使用该类。

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

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

如果你想尝试其他东西,请告诉我。

答案 1 :(得分: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
相关问题