如何编写CanCanCan能否让用户只读取他们的数据?

问题描述 投票:1回答:2

如何限制用户访问权限,以便用户只能阅读自己的记录?

我试过了:

def initialize(user)
  can :read, User, :id => user.id

还有这个:

def initialize(user)
  can :read, user

但我仍然可以访问索引和显示中的每个用户。我在UsersController中有authorize_resource。

相关文件供参考:https://github.com/CanCanCommunity/cancancan/wiki/Defining-Abilities

ruby-on-rails authorization cancan cancancan
2个回答
0
投票
:read != :show

:read == [:show, :index]

不幸的是,我没有设置测试它所以它在黑暗中拍摄。

can :show, User, :id => user.id

0
投票

似乎放

authorize! :show, @user

在节目动作和

@users = User.accessible_by(current_ability)

在索引操作中使用以下方法解决了我的问题:

def initialize(user)
  can :read, User, :id => user.id

我现在可以看到我应该使用load_and_authorize_resource而不仅仅是authorize_resource,因为它会自动添加那些。

© www.soinside.com 2019 - 2024. All rights reserved.