使用CanCan将索引页面上的视图限制为user_id

时间:2012-09-17 16:39:09

标签: ruby-on-rails list devise indexing cancan

我正在使用Devise和Cancan进行rails 3.2.6应用程序。在应用程序中,我允许用户创建一个文档,其中包含在表单中收集的一些信息。然后,我想允许用户在localhost:3000 / users / 1 / document文档索引页面上列出他们的文档,这是有效的。什么是无效的,我试图通过将/ users /:id / documents替换为另一个号码来限制用户能够看到其他人的文档。

我正在使用cancan并尝试过两种

可以:index,Document,:user_id =>用户身份  can:read,Document,:user_id => user.id

然后在Document控制器索引方法

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

也尝试使用:index ......但这不起作用。我也在使用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, Document, :user_id => user.id 
        can :update, Document, :user_id => user.id 
      end 
    end 
  end 
end

2 个答案:

答案 0 :(得分:2)

您必须确保未登录的用户以及user.id与文档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, Document, :user_id => user.id

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

    end

  end
end

请注意,如果您说cancan已经在工作,那么您很可能没有像can :read, :allcan :read, Document这样的任何一条线路。

答案 1 :(得分:0)

在你的情况下,你应该写下你的能力课

def initialize(user)
  can :manage, Document do |document|
    document.user == user
  end  
end

这将检查文档是否属于登录用户。如果是,则返回true,否则为假。

有关如何使用块处理复杂授权的更多详细信息,

https://github.com/ryanb/cancan/wiki/Defining-Abilities-with-Blocks