加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 使用CanCan将索引页面上的视图限制为user_id

发布时间:2020-12-17 02:14:07 所属栏目:百科 来源:网络整理
导读:我正在使用Devise和Cancan进行rails 3.2.6应用程序.在应用程序中,我允许用户创建一个文档,其中包含在表单中收集的一些信息.然后,我想允许用户在localhost:3000 / users / 1 / document文档索引页面上列出他们的文档,这是有效的.什么是无效的,我试图通过用另
我正在使用Devise和Cancan进行rails 3.2.6应用程序.在应用程序中,我允许用户创建一个文档,其中包含在表单中收集的一些信息.然后,我想允许用户在localhost:3000 / users / 1 / document文档索引页面上列出他们的文档,这是有效的.什么是无效的,我试图通过用另一个数字替换/ users /:id / documents来限制用户能够看到其他人的文档.

我正在使用康康,并尝试过两者

可以:index,Document,:user_id =>用户身份
?can:read,:user_id =>用户身份

然后在Document控制器索引方法上

if can? :read,Document
 @documents = @user.documents
else
 redirect_to root_path
end

也试过:索引以及…但这不起作用.我也在使用load_and_authorize_resource ..

对我失踪的任何想法?

我会说,cancan正在为我的用户管理和用户控制器工作,管理员可以创建,列出和编辑用户,所以我知道cancan一般都在工作.它还用于更新和删除用户文档.只是索引功能不起作用.

class Ability 

include CanCan::Ability 

  def initialize(user) 

    user ||= User.new # guest user (not logged in) 
    if user.id 
      if user.has_role? :user 
        can :create,Document 
        can :read,:user_id => user.id 
        can :update,:user_id => user.id 
      end 
    end 
  end 
end

解决方法

您必须确保未登录的用户以及user.id与Document的user_id(文档所有者)不同的用户无权读取所有文档.

class Ability
  include CanCan::Ability

  def initialize(account)

    user ||= User.new  #non-logged-in user

    # logged in users
    if user.id and user.has_role?(:user)

      #content owners
      can :manage,:user_id => user.id

      #other logged-in users
      can [:show,:create],Document

    end

  end
end

小心你没有像can一样的行:read,:all或can:read,Document如果你说cancan已经在工作,你很可能会在某处提供权限.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读