【问题标题】:How to write CanCanCan Ability for user to read only their data?如何编写 CanCanCan 用户只能读取其数据的能力?
【发布时间】:2019-02-12 12:10:35
【问题描述】:

您如何限制用户访问以使用户只能读取自己的记录?

我试过了:

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


    【解决方案1】:
    :read != :show
    
    :read == [:show, :index]
    

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

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

    【讨论】:

    • 谢谢,但不幸的是,我仍然可以显示其他用户的页面
    【解决方案2】:

    好像放了

    authorize! :show, @user
    

    在表演动作中和

    @users = User.accessible_by(current_ability)
    

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-16
      • 1970-01-01
      • 1970-01-01
      • 2015-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多